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/wheel/config.py
|
apply
|
python
|
def apply(key, value):
'''
Set a single key
.. note::
This will strip comments from your config file
'''
path = __opts__['conf_file']
if os.path.isdir(path):
path = os.path.join(path, 'master')
data = values()
data[key] = value
with salt.utils.files.fopen(path, 'w+') as fp_:
salt.utils.yaml.safe_dump(data, default_flow_style=False)
|
Set a single key
.. note::
This will strip comments from your config file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/config.py#L30-L44
|
[
"def values():\n '''\n Return the raw values of the config file\n '''\n data = salt.config.master_config(__opts__['conf_file'])\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",
"def safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the master configuration file
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
# Import salt libs
import salt.config
import salt.utils.files
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def values():
'''
Return the raw values of the config file
'''
data = salt.config.master_config(__opts__['conf_file'])
return data
def update_config(file_name, yaml_contents):
'''
Update master config with
``yaml_contents``.
Writes ``yaml_contents`` to a file named
``file_name.conf`` under the folder
specified by ``default_include``.
This folder is named ``master.d`` by
default. Please look at
:conf_master:`include-configuration`
for more information.
Example low data:
.. code-block:: python
data = {
'username': 'salt',
'password': 'salt',
'fun': 'config.update_config',
'file_name': 'gui',
'yaml_contents': {'id': 1},
'client': 'wheel',
'eauth': 'pam',
}
'''
file_name = '{0}{1}'.format(file_name, '.conf')
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
log.debug('Creating directory %s', dir_path)
os.makedirs(dir_path, 0o755)
file_path = os.path.join(dir_path, file_name)
with salt.utils.files.fopen(file_path, 'w') as fp_:
fp_.write(yaml_out)
return 'Wrote {0}'.format(file_name)
except (IOError, OSError, salt.utils.yaml.YAMLError, ValueError) as err:
return six.text_type(err)
|
saltstack/salt
|
salt/wheel/config.py
|
update_config
|
python
|
def update_config(file_name, yaml_contents):
'''
Update master config with
``yaml_contents``.
Writes ``yaml_contents`` to a file named
``file_name.conf`` under the folder
specified by ``default_include``.
This folder is named ``master.d`` by
default. Please look at
:conf_master:`include-configuration`
for more information.
Example low data:
.. code-block:: python
data = {
'username': 'salt',
'password': 'salt',
'fun': 'config.update_config',
'file_name': 'gui',
'yaml_contents': {'id': 1},
'client': 'wheel',
'eauth': 'pam',
}
'''
file_name = '{0}{1}'.format(file_name, '.conf')
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
log.debug('Creating directory %s', dir_path)
os.makedirs(dir_path, 0o755)
file_path = os.path.join(dir_path, file_name)
with salt.utils.files.fopen(file_path, 'w') as fp_:
fp_.write(yaml_out)
return 'Wrote {0}'.format(file_name)
except (IOError, OSError, salt.utils.yaml.YAMLError, ValueError) as err:
return six.text_type(err)
|
Update master config with
``yaml_contents``.
Writes ``yaml_contents`` to a file named
``file_name.conf`` under the folder
specified by ``default_include``.
This folder is named ``master.d`` by
default. Please look at
:conf_master:`include-configuration`
for more information.
Example low data:
.. code-block:: python
data = {
'username': 'salt',
'password': 'salt',
'fun': 'config.update_config',
'file_name': 'gui',
'yaml_contents': {'id': 1},
'client': 'wheel',
'eauth': 'pam',
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/wheel/config.py#L47-L90
|
[
"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 safe_dump(data, stream=None, **kwargs):\n '''\n Use a custom dumper to ensure that defaultdict and OrderedDict are\n represented properly. Ensure that unicode strings are encoded unless\n explicitly told not to.\n '''\n if 'allow_unicode' not in kwargs:\n kwargs['allow_unicode'] = True\n return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Manage the master configuration file
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
# Import salt libs
import salt.config
import salt.utils.files
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
log = logging.getLogger(__name__)
def values():
'''
Return the raw values of the config file
'''
data = salt.config.master_config(__opts__['conf_file'])
return data
def apply(key, value):
'''
Set a single key
.. note::
This will strip comments from your config file
'''
path = __opts__['conf_file']
if os.path.isdir(path):
path = os.path.join(path, 'master')
data = values()
data[key] = value
with salt.utils.files.fopen(path, 'w+') as fp_:
salt.utils.yaml.safe_dump(data, default_flow_style=False)
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_get_ppa_info_from_launchpad
|
python
|
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
|
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L125-L141
|
[
"def load(fp, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.load\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n return kwargs.pop('_json_module', json).load(fp, **kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_call_apt
|
python
|
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
|
Call apt* utilities.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L161-L175
|
[
"def has_scope(context=None):\n '''\n Scopes were introduced in systemd 205, this function returns a boolean\n which is true when the minion is systemd-booted and running systemd>=205.\n '''\n if not booted(context):\n return False\n _sd_version = version(context)\n if _sd_version is None:\n return False\n return _sd_version >= 205\n",
"def get_module_environment(env=None, function=None):\n '''\n Get module optional environment.\n\n To setup an environment option for a particular module,\n add either pillar or config at the minion as follows:\n\n system-environment:\n modules:\n pkg:\n _:\n LC_ALL: en_GB.UTF-8\n FOO: bar\n install:\n HELLO: world\n states:\n pkg:\n _:\n LC_ALL: en_US.Latin-1\n NAME: Fred\n\n So this will export the environment to all the modules,\n states, returnes etc. And calling this function with the globals()\n in that context will fetch the environment for further reuse.\n\n Underscore '_' exports environment for all functions within the module.\n If you want to specifially export environment only for one function,\n specify it as in the example above \"install\".\n\n First will be fetched configuration, where virtual name goes first,\n then the physical name of the module overrides the virtual settings.\n Then pillar settings will override the configuration in the same order.\n\n :param env:\n :param function: name of a particular function\n :return: dict\n '''\n result = {}\n if not env:\n env = {}\n for env_src in [env.get('__opts__', {}), env.get('__pillar__', {})]:\n fname = env.get('__file__', '')\n physical_name = os.path.basename(fname).split('.')[0]\n section = os.path.basename(os.path.dirname(fname))\n m_names = [env.get('__virtualname__')]\n if physical_name not in m_names:\n m_names.append(physical_name)\n for m_name in m_names:\n if not m_name:\n continue\n result.update(env_src.get('system-environment', {}).get(\n section, {}).get(m_name, {}).get('_', {}).copy())\n if function is not None:\n result.update(env_src.get('system-environment', {}).get(\n section, {}).get(m_name, {}).get(function, {}).copy())\n\n return result\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
refresh_db
|
python
|
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
|
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L297-L376
|
[
"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 clear_rtag(opts):\n '''\n Remove the rtag file\n '''\n try:\n os.remove(rtag(opts))\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n # Using __str__() here to get the fully-formatted error message\n # (error number, error message, path)\n log.warning('Encountered error removing rtag: %s', exc.__str__())\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
install
|
python
|
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L379-L785
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def _resolve_deps(name, pkgs, **kwargs):\n '''\n Installs missing dependencies and marks them as auto installed so they\n are removed when no more manually installed packages depend on them.\n\n .. versionadded:: 2014.7.0\n\n :depends: - python-apt module\n '''\n missing_deps = []\n for pkg_file in pkgs:\n deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())\n if deb.check():\n missing_deps.extend(deb.missing_deps)\n\n if missing_deps:\n cmd = ['apt-get', '-q', '-y']\n cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']\n cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']\n cmd.append('install')\n cmd.extend(missing_deps)\n\n ret = __salt__['cmd.retcode'](\n cmd,\n env=kwargs.get('env'),\n python_shell=False\n )\n\n if ret != 0:\n raise CommandExecutionError(\n 'Error: unable to resolve dependencies for: {0}'.format(name)\n )\n else:\n try:\n cmd = ['apt-mark', 'auto'] + missing_deps\n __salt__['cmd.run'](\n cmd,\n env=kwargs.get('env'),\n python_shell=False\n )\n except MinionError as exc:\n raise CommandExecutionError(exc)\n return\n",
"def list_pkgs(versions_as_list=False,\n removed=False,\n purge_desired=False,\n **kwargs): # pylint: disable=W0613\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n removed\n If ``True``, then only packages which have been removed (but not\n purged) will be returned.\n\n purge_desired\n If ``True``, then only packages which have been marked to be purged,\n but can't be purged due to their status as dependencies for other\n installed packages, will be returned. Note that these packages will\n appear in installed\n\n .. versionchanged:: 2014.1.1\n\n Packages in this state now correctly show up in the output of this\n function.\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n removed = salt.utils.data.is_true(removed)\n purge_desired = salt.utils.data.is_true(purge_desired)\n\n if 'pkg.list_pkgs' in __context__:\n if removed:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}\n cmd = ['dpkg-query', '--showformat',\n '${Status} ${Package} ${Version} ${Architecture}\\n', '-W']\n\n out = __salt__['cmd.run_stdout'](\n cmd,\n output_loglevel='trace',\n python_shell=False)\n # Typical lines of output:\n # install ok installed zsh 4.3.17-1ubuntu1 amd64\n # deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64\n for line in out.splitlines():\n cols = line.split()\n try:\n linetype, status, name, version_num, arch = \\\n [cols[x] for x in (0, 2, 3, 4, 5)]\n except (ValueError, IndexError):\n continue\n if __grains__.get('cpuarch', '') == 'x86_64':\n osarch = __grains__.get('osarch', '')\n if arch != 'all' and osarch == 'amd64' and osarch != arch:\n name += ':{0}'.format(arch)\n if cols:\n if ('install' in linetype or 'hold' in linetype) and \\\n 'installed' in status:\n __salt__['pkg_resource.add_pkg'](ret['installed'],\n name,\n version_num)\n elif 'deinstall' in linetype:\n __salt__['pkg_resource.add_pkg'](ret['removed'],\n name,\n version_num)\n elif 'purge' in linetype and status == 'installed':\n __salt__['pkg_resource.add_pkg'](ret['purge_desired'],\n name,\n version_num)\n\n for pkglist_type in ('installed', 'removed', 'purge_desired'):\n __salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])\n\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n\n if removed:\n ret = ret['removed']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def latest_version(*names, **kwargs):\n '''\n Return the latest version of the named package available for upgrade or\n installation. If more than one package name is specified, a dict of\n name/version pairs is returned.\n\n If the latest version of a given package is already installed, an empty\n string will be returned for that package.\n\n A specific repo can be requested using the ``fromrepo`` keyword argument.\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.latest_version <package name>\n salt '*' pkg.latest_version <package name> fromrepo=unstable\n salt '*' pkg.latest_version <package1> <package2> <package3> ...\n '''\n refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))\n show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))\n if 'repo' in kwargs:\n raise SaltInvocationError(\n 'The \\'repo\\' argument is invalid, use \\'fromrepo\\' instead'\n )\n fromrepo = kwargs.pop('fromrepo', None)\n cache_valid_time = kwargs.pop('cache_valid_time', 0)\n\n if not names:\n return ''\n ret = {}\n # Initialize the dict with empty strings\n for name in names:\n ret[name] = ''\n pkgs = list_pkgs(versions_as_list=True)\n repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \\\n if fromrepo else None\n\n # Refresh before looking for the latest version available\n if refresh:\n refresh_db(cache_valid_time)\n\n for name in names:\n cmd = ['apt-cache', '-q', 'policy', name]\n if repo is not None:\n cmd.extend(repo)\n out = _call_apt(cmd, scope=False)\n\n candidate = ''\n for line in salt.utils.itertools.split(out['stdout'], '\\n'):\n if 'Candidate' in line:\n comps = line.split()\n if len(comps) >= 2:\n candidate = comps[-1]\n if candidate.lower() == '(none)':\n candidate = ''\n break\n\n installed = pkgs.get(name, [])\n if not installed:\n ret[name] = candidate\n elif installed and show_installed:\n ret[name] = candidate\n elif candidate:\n # If there are no installed versions that are greater than or equal\n # to the install candidate, then the candidate is an upgrade, so\n # add it to the return dict\n if not any(\n (salt.utils.versions.compare(ver1=x,\n oper='>=',\n ver2=candidate,\n cmp_func=version_cmp)\n for x in installed)\n ):\n ret[name] = candidate\n\n # Return a string if only one package name passed\n if len(names) == 1:\n return ret[names[0]]\n return ret\n",
"def refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def _parse_env(env):\n if not env:\n env = {}\n if isinstance(env, list):\n env = salt.utils.data.repack_dictlist(env)\n if not isinstance(env, dict):\n env = {}\n return env\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import\n '''\n .. versionadded:: 2017.7.0\n\n Returns all available packages. Optionally, package names (and name globs)\n can be passed and the results will be filtered to packages matching those\n names.\n\n This function can be helpful in discovering the version or repo to specify\n in a :mod:`pkg.installed <salt.states.pkg.installed>` state.\n\n The return data will be a dictionary mapping package names to a list of\n version numbers, ordered from newest to oldest. For example:\n\n .. code-block:: python\n\n {\n 'bash': ['4.3-14ubuntu1.1',\n '4.3-14ubuntu1'],\n 'nginx': ['1.10.0-0ubuntu0.16.04.4',\n '1.9.15-0ubuntu1']\n }\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.list_repo_pkgs\n salt '*' pkg.list_repo_pkgs foo bar baz\n '''\n if args:\n # Get only information about packages in args\n cmd = ['apt-cache', 'show'] + [arg for arg in args]\n else:\n # Get information about all available packages\n cmd = ['apt-cache', 'dump']\n\n out = _call_apt(cmd, scope=False, ignore_retcode=True)\n\n ret = {}\n pkg_name = None\n skip_pkg = False\n new_pkg = re.compile('^Package: (.+)')\n for line in salt.utils.itertools.split(out['stdout'], '\\n'):\n if not line.strip():\n continue\n try:\n cur_pkg = new_pkg.match(line).group(1)\n except AttributeError:\n pass\n else:\n if cur_pkg != pkg_name:\n pkg_name = cur_pkg\n continue\n comps = line.strip().split(None, 1)\n if comps[0] == 'Version:':\n ret.setdefault(pkg_name, []).append(comps[1])\n\n return ret\n",
"def get_selections(pattern=None, state=None):\n '''\n View package state from the dpkg database.\n\n Returns a dict of dicts containing the state, and package names:\n\n .. code-block:: python\n\n {'<host>':\n {'<state>': ['pkg1',\n ...\n ]\n },\n ...\n }\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_selections\n salt '*' pkg.get_selections 'python-*'\n salt '*' pkg.get_selections state=hold\n salt '*' pkg.get_selections 'openssh*' state=hold\n '''\n ret = {}\n cmd = ['dpkg', '--get-selections']\n cmd.append(pattern if pattern else '*')\n stdout = __salt__['cmd.run_stdout'](cmd,\n output_loglevel='trace',\n python_shell=False)\n ret = _parse_selections(stdout)\n if state:\n return {state: ret.get(state, [])}\n return ret\n",
"def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613\n '''\n .. versionadded:: 2014.7.0\n\n Set package in 'hold' state, meaning it will not be upgraded.\n\n name\n The name of the package, e.g., 'tmux'\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.hold <package name>\n\n pkgs\n A list of packages to hold. Must be passed as a python list.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.hold pkgs='[\"foo\", \"bar\"]'\n '''\n if not name and not pkgs and not sources:\n raise SaltInvocationError(\n 'One of name, pkgs, or sources must be specified.'\n )\n if pkgs and sources:\n raise SaltInvocationError(\n 'Only one of pkgs or sources can be specified.'\n )\n\n targets = []\n if pkgs:\n targets.extend(pkgs)\n elif sources:\n for source in sources:\n targets.append(next(iter(source)))\n else:\n targets.append(name)\n\n ret = {}\n for target in targets:\n if isinstance(target, dict):\n target = next(iter(target))\n\n ret[target] = {'name': target,\n 'changes': {},\n 'result': False,\n 'comment': ''}\n\n state = get_selections(pattern=target, state='hold')\n if not state:\n ret[target]['comment'] = ('Package {0} not currently held.'\n .format(target))\n elif not salt.utils.data.is_true(state.get('hold', False)):\n if 'test' in __opts__ and __opts__['test']:\n ret[target].update(result=None)\n ret[target]['comment'] = ('Package {0} is set to be held.'\n .format(target))\n else:\n result = set_selections(selection={'hold': [target]})\n ret[target].update(changes=result[target], result=True)\n ret[target]['comment'] = ('Package {0} is now being held.'\n .format(target))\n else:\n ret[target].update(result=True)\n ret[target]['comment'] = ('Package {0} is already set to be held.'\n .format(target))\n return ret\n",
"def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613\n '''\n .. versionadded:: 2014.7.0\n\n Set package current in 'hold' state to install state,\n meaning it will be upgraded.\n\n name\n The name of the package, e.g., 'tmux'\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.unhold <package name>\n\n pkgs\n A list of packages to unhold. Must be passed as a python list.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.unhold pkgs='[\"foo\", \"bar\"]'\n '''\n if not name and not pkgs and not sources:\n raise SaltInvocationError(\n 'One of name, pkgs, or sources must be specified.'\n )\n if pkgs and sources:\n raise SaltInvocationError(\n 'Only one of pkgs or sources can be specified.'\n )\n\n targets = []\n if pkgs:\n targets.extend(pkgs)\n elif sources:\n for source in sources:\n targets.append(next(iter(source)))\n else:\n targets.append(name)\n\n ret = {}\n for target in targets:\n if isinstance(target, dict):\n target = next(iter(target))\n\n ret[target] = {'name': target,\n 'changes': {},\n 'result': False,\n 'comment': ''}\n\n state = get_selections(pattern=target)\n if not state:\n ret[target]['comment'] = ('Package {0} does not have a state.'\n .format(target))\n elif salt.utils.data.is_true(state.get('hold', False)):\n if 'test' in __opts__ and __opts__['test']:\n ret[target].update(result=None)\n ret[target]['comment'] = ('Package {0} is set not to be '\n 'held.'.format(target))\n else:\n result = set_selections(selection={'install': [target]})\n ret[target].update(changes=result[target], result=True)\n ret[target]['comment'] = ('Package {0} is no longer being '\n 'held.'.format(target))\n else:\n ret[target].update(result=True)\n ret[target]['comment'] = ('Package {0} is already set not to be '\n 'held.'.format(target))\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_uninstall
|
python
|
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
|
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L788-L834
|
[
"def list_pkgs(versions_as_list=False,\n removed=False,\n purge_desired=False,\n **kwargs): # pylint: disable=W0613\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n removed\n If ``True``, then only packages which have been removed (but not\n purged) will be returned.\n\n purge_desired\n If ``True``, then only packages which have been marked to be purged,\n but can't be purged due to their status as dependencies for other\n installed packages, will be returned. Note that these packages will\n appear in installed\n\n .. versionchanged:: 2014.1.1\n\n Packages in this state now correctly show up in the output of this\n function.\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n removed = salt.utils.data.is_true(removed)\n purge_desired = salt.utils.data.is_true(purge_desired)\n\n if 'pkg.list_pkgs' in __context__:\n if removed:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}\n cmd = ['dpkg-query', '--showformat',\n '${Status} ${Package} ${Version} ${Architecture}\\n', '-W']\n\n out = __salt__['cmd.run_stdout'](\n cmd,\n output_loglevel='trace',\n python_shell=False)\n # Typical lines of output:\n # install ok installed zsh 4.3.17-1ubuntu1 amd64\n # deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64\n for line in out.splitlines():\n cols = line.split()\n try:\n linetype, status, name, version_num, arch = \\\n [cols[x] for x in (0, 2, 3, 4, 5)]\n except (ValueError, IndexError):\n continue\n if __grains__.get('cpuarch', '') == 'x86_64':\n osarch = __grains__.get('osarch', '')\n if arch != 'all' and osarch == 'amd64' and osarch != arch:\n name += ':{0}'.format(arch)\n if cols:\n if ('install' in linetype or 'hold' in linetype) and \\\n 'installed' in status:\n __salt__['pkg_resource.add_pkg'](ret['installed'],\n name,\n version_num)\n elif 'deinstall' in linetype:\n __salt__['pkg_resource.add_pkg'](ret['removed'],\n name,\n version_num)\n elif 'purge' in linetype and status == 'installed':\n __salt__['pkg_resource.add_pkg'](ret['purge_desired'],\n name,\n version_num)\n\n for pkglist_type in ('installed', 'removed', 'purge_desired'):\n __salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])\n\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n\n if removed:\n ret = ret['removed']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _parse_env(env):\n if not env:\n env = {}\n if isinstance(env, list):\n env = salt.utils.data.repack_dictlist(env)\n if not isinstance(env, dict):\n env = {}\n return env\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
autoremove
|
python
|
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
|
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L837-L889
|
[
"def list_pkgs(versions_as_list=False,\n removed=False,\n purge_desired=False,\n **kwargs): # pylint: disable=W0613\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n removed\n If ``True``, then only packages which have been removed (but not\n purged) will be returned.\n\n purge_desired\n If ``True``, then only packages which have been marked to be purged,\n but can't be purged due to their status as dependencies for other\n installed packages, will be returned. Note that these packages will\n appear in installed\n\n .. versionchanged:: 2014.1.1\n\n Packages in this state now correctly show up in the output of this\n function.\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n removed = salt.utils.data.is_true(removed)\n purge_desired = salt.utils.data.is_true(purge_desired)\n\n if 'pkg.list_pkgs' in __context__:\n if removed:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}\n cmd = ['dpkg-query', '--showformat',\n '${Status} ${Package} ${Version} ${Architecture}\\n', '-W']\n\n out = __salt__['cmd.run_stdout'](\n cmd,\n output_loglevel='trace',\n python_shell=False)\n # Typical lines of output:\n # install ok installed zsh 4.3.17-1ubuntu1 amd64\n # deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64\n for line in out.splitlines():\n cols = line.split()\n try:\n linetype, status, name, version_num, arch = \\\n [cols[x] for x in (0, 2, 3, 4, 5)]\n except (ValueError, IndexError):\n continue\n if __grains__.get('cpuarch', '') == 'x86_64':\n osarch = __grains__.get('osarch', '')\n if arch != 'all' and osarch == 'amd64' and osarch != arch:\n name += ':{0}'.format(arch)\n if cols:\n if ('install' in linetype or 'hold' in linetype) and \\\n 'installed' in status:\n __salt__['pkg_resource.add_pkg'](ret['installed'],\n name,\n version_num)\n elif 'deinstall' in linetype:\n __salt__['pkg_resource.add_pkg'](ret['removed'],\n name,\n version_num)\n elif 'purge' in linetype and status == 'installed':\n __salt__['pkg_resource.add_pkg'](ret['purge_desired'],\n name,\n version_num)\n\n for pkglist_type in ('installed', 'removed', 'purge_desired'):\n __salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])\n\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n\n if removed:\n ret = ret['removed']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L892-L933
|
[
"def _uninstall(action='remove', name=None, pkgs=None, **kwargs):\n '''\n remove and purge do identical things but with different apt-get commands,\n this function performs the common logic.\n '''\n try:\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]\n except MinionError as exc:\n raise CommandExecutionError(exc)\n\n old = list_pkgs()\n old_removed = list_pkgs(removed=True)\n targets = [x for x in pkg_params if x in old]\n if action == 'purge':\n targets.extend([x for x in pkg_params if x in old_removed])\n if not targets:\n return {}\n cmd = ['apt-get', '-q', '-y', action]\n cmd.extend(targets)\n env = _parse_env(kwargs.get('env'))\n env.update(DPKG_ENV_VARS.copy())\n out = _call_apt(cmd, env=env)\n if out['retcode'] != 0 and out['stderr']:\n errors = [out['stderr']]\n else:\n errors = []\n\n __context__.pop('pkg.list_pkgs', None)\n new = list_pkgs()\n new_removed = list_pkgs(removed=True)\n\n changes = salt.utils.data.compare_dicts(old, new)\n if action == 'purge':\n ret = {\n 'removed': salt.utils.data.compare_dicts(old_removed, new_removed),\n 'installed': changes\n }\n else:\n ret = changes\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered removing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
purge
|
python
|
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L936-L977
|
[
"def _uninstall(action='remove', name=None, pkgs=None, **kwargs):\n '''\n remove and purge do identical things but with different apt-get commands,\n this function performs the common logic.\n '''\n try:\n pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]\n except MinionError as exc:\n raise CommandExecutionError(exc)\n\n old = list_pkgs()\n old_removed = list_pkgs(removed=True)\n targets = [x for x in pkg_params if x in old]\n if action == 'purge':\n targets.extend([x for x in pkg_params if x in old_removed])\n if not targets:\n return {}\n cmd = ['apt-get', '-q', '-y', action]\n cmd.extend(targets)\n env = _parse_env(kwargs.get('env'))\n env.update(DPKG_ENV_VARS.copy())\n out = _call_apt(cmd, env=env)\n if out['retcode'] != 0 and out['stderr']:\n errors = [out['stderr']]\n else:\n errors = []\n\n __context__.pop('pkg.list_pkgs', None)\n new = list_pkgs()\n new_removed = list_pkgs(removed=True)\n\n changes = salt.utils.data.compare_dicts(old, new)\n if action == 'purge':\n ret = {\n 'removed': salt.utils.data.compare_dicts(old_removed, new_removed),\n 'installed': changes\n }\n else:\n ret = changes\n\n if errors:\n raise CommandExecutionError(\n 'Problem encountered removing package(s)',\n info={'errors': errors, 'changes': ret}\n )\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
upgrade
|
python
|
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
|
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L980-L1066
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False,\n removed=False,\n purge_desired=False,\n **kwargs): # pylint: disable=W0613\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n removed\n If ``True``, then only packages which have been removed (but not\n purged) will be returned.\n\n purge_desired\n If ``True``, then only packages which have been marked to be purged,\n but can't be purged due to their status as dependencies for other\n installed packages, will be returned. Note that these packages will\n appear in installed\n\n .. versionchanged:: 2014.1.1\n\n Packages in this state now correctly show up in the output of this\n function.\n\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n removed = salt.utils.data.is_true(removed)\n purge_desired = salt.utils.data.is_true(purge_desired)\n\n if 'pkg.list_pkgs' in __context__:\n if removed:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}\n cmd = ['dpkg-query', '--showformat',\n '${Status} ${Package} ${Version} ${Architecture}\\n', '-W']\n\n out = __salt__['cmd.run_stdout'](\n cmd,\n output_loglevel='trace',\n python_shell=False)\n # Typical lines of output:\n # install ok installed zsh 4.3.17-1ubuntu1 amd64\n # deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64\n for line in out.splitlines():\n cols = line.split()\n try:\n linetype, status, name, version_num, arch = \\\n [cols[x] for x in (0, 2, 3, 4, 5)]\n except (ValueError, IndexError):\n continue\n if __grains__.get('cpuarch', '') == 'x86_64':\n osarch = __grains__.get('osarch', '')\n if arch != 'all' and osarch == 'amd64' and osarch != arch:\n name += ':{0}'.format(arch)\n if cols:\n if ('install' in linetype or 'hold' in linetype) and \\\n 'installed' in status:\n __salt__['pkg_resource.add_pkg'](ret['installed'],\n name,\n version_num)\n elif 'deinstall' in linetype:\n __salt__['pkg_resource.add_pkg'](ret['removed'],\n name,\n version_num)\n elif 'purge' in linetype and status == 'installed':\n __salt__['pkg_resource.add_pkg'](ret['purge_desired'],\n name,\n version_num)\n\n for pkglist_type in ('installed', 'removed', 'purge_desired'):\n __salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])\n\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n\n if removed:\n ret = ret['removed']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])\n if not purge_desired:\n ret.update(__context__['pkg.list_pkgs']['installed'])\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
hold
|
python
|
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
|
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1069-L1139
|
[
"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 get_selections(pattern=None, state=None):\n '''\n View package state from the dpkg database.\n\n Returns a dict of dicts containing the state, and package names:\n\n .. code-block:: python\n\n {'<host>':\n {'<state>': ['pkg1',\n ...\n ]\n },\n ...\n }\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_selections\n salt '*' pkg.get_selections 'python-*'\n salt '*' pkg.get_selections state=hold\n salt '*' pkg.get_selections 'openssh*' state=hold\n '''\n ret = {}\n cmd = ['dpkg', '--get-selections']\n cmd.append(pattern if pattern else '*')\n stdout = __salt__['cmd.run_stdout'](cmd,\n output_loglevel='trace',\n python_shell=False)\n ret = _parse_selections(stdout)\n if state:\n return {state: ret.get(state, [])}\n return ret\n",
"def set_selections(path=None, selection=None, clear=False, saltenv='base'):\n '''\n Change package state in the dpkg database.\n\n The state can be any one of, documented in ``dpkg(1)``:\n\n - install\n - hold\n - deinstall\n - purge\n\n This command is commonly used to mark specific packages to be held from\n being upgraded, that is, to be kept at a certain version. When a state is\n changed to anything but being held, then it is typically followed by\n ``apt-get -u dselect-upgrade``.\n\n Note: Be careful with the ``clear`` argument, since it will start\n with setting all packages to deinstall state.\n\n Returns a dict of dicts containing the package names, and the new and old\n versions:\n\n .. code-block:: python\n\n {'<host>':\n {'<package>': {'new': '<new-state>',\n 'old': '<old-state>'}\n },\n ...\n }\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.set_selections selection='{\"install\": [\"netcat\"]}'\n salt '*' pkg.set_selections selection='{\"hold\": [\"openssh-server\", \"openssh-client\"]}'\n salt '*' pkg.set_selections salt://path/to/file\n salt '*' pkg.set_selections salt://path/to/file clear=True\n '''\n ret = {}\n if not path and not selection:\n return ret\n if path and selection:\n err = ('The \\'selection\\' and \\'path\\' arguments to '\n 'pkg.set_selections are mutually exclusive, and cannot be '\n 'specified together')\n raise SaltInvocationError(err)\n\n if isinstance(selection, six.string_types):\n try:\n selection = salt.utils.yaml.safe_load(selection)\n except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:\n raise SaltInvocationError(\n 'Improperly-formatted selection: {0}'.format(exc)\n )\n\n if path:\n path = __salt__['cp.cache_file'](path, saltenv)\n with salt.utils.files.fopen(path, 'r') as ifile:\n content = [salt.utils.stringutils.to_unicode(x)\n for x in ifile.readlines()]\n selection = _parse_selections(content)\n\n if selection:\n valid_states = ('install', 'hold', 'deinstall', 'purge')\n bad_states = [x for x in selection if x not in valid_states]\n if bad_states:\n raise SaltInvocationError(\n 'Invalid state(s): {0}'.format(', '.join(bad_states))\n )\n\n if clear:\n cmd = ['dpkg', '--clear-selections']\n if not __opts__['test']:\n result = _call_apt(cmd, scope=False)\n if result['retcode'] != 0:\n err = ('Running dpkg --clear-selections failed: '\n '{0}'.format(result['stderr']))\n log.error(err)\n raise CommandExecutionError(err)\n\n sel_revmap = {}\n for _state, _pkgs in six.iteritems(get_selections()):\n sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))\n\n for _state, _pkgs in six.iteritems(selection):\n for _pkg in _pkgs:\n if _state == sel_revmap.get(_pkg):\n continue\n cmd = ['dpkg', '--set-selections']\n cmd_in = '{0} {1}'.format(_pkg, _state)\n if not __opts__['test']:\n result = _call_apt(cmd, scope=False, stdin=cmd_in)\n if result['retcode'] != 0:\n log.error(\n 'failed to set state %s for package %s',\n _state, _pkg\n )\n else:\n ret[_pkg] = {'old': sel_revmap.get(_pkg),\n 'new': _state}\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
list_pkgs
|
python
|
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
|
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1216-L1313
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_get_upgradable
|
python
|
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
|
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1316-L1361
|
[
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"_get = lambda l, k: l[keys.index(k)]\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
list_upgrades
|
python
|
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
|
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1364-L1392
|
[
"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 refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def _get_upgradable(dist_upgrade=True, **kwargs):\n '''\n Utility function to get upgradable packages\n\n Sample return data:\n { 'pkgname': '1.2.3-45', ... }\n '''\n\n cmd = ['apt-get', '--just-print']\n if dist_upgrade:\n cmd.append('dist-upgrade')\n else:\n cmd.append('upgrade')\n try:\n cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])\n except KeyError:\n pass\n\n call = _call_apt(cmd)\n if call['retcode'] != 0:\n msg = 'Failed to get upgrades'\n for key in ('stderr', 'stdout'):\n if call[key]:\n msg += ': ' + call[key]\n break\n raise CommandExecutionError(msg)\n else:\n out = call['stdout']\n\n # rexp parses lines that look like the following:\n # Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])\n rexp = re.compile('(?m)^Conf '\n '([^ ]+) ' # Package name\n r'\\(([^ ]+)') # Version\n keys = ['name', 'version']\n _get = lambda l, k: l[keys.index(k)]\n\n upgrades = rexp.findall(out)\n\n ret = {}\n for line in upgrades:\n name = _get(line, 'name')\n version_num = _get(line, 'version')\n ret[name] = version_num\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
version_cmp
|
python
|
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
|
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1408-L1461
|
[
"normalize = lambda x: six.text_type(x).split(':', 1)[-1] \\\n if ignore_epoch else six.text_type(x)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_split_repo_str
|
python
|
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
|
Return APT source entry as a tuple.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1464-L1469
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_consolidate_repo_sources
|
python
|
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
|
Consolidate APT sources.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1472-L1513
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
list_repo_pkgs
|
python
|
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
|
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1516-L1574
|
[
"def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_skip_source
|
python
|
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
|
Decide to skip source or not.
:param source:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1577-L1595
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
list_repos
|
python
|
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
|
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1598-L1626
|
[
"def _check_apt():\n '''\n Abort if python-apt is not installed\n '''\n if not HAS_APT:\n raise CommandExecutionError(\n 'Error: \\'python-apt\\' package not installed'\n )\n",
"def strip_uri(repo):\n '''\n Remove the trailing slash from the URI in a repo definition\n '''\n splits = repo.split()\n for idx in range(len(splits)):\n if any(splits[idx].startswith(x)\n for x in ('http://', 'https://', 'ftp://')):\n splits[idx] = splits[idx].rstrip('/')\n return ' '.join(splits)\n",
"def _skip_source(source):\n '''\n Decide to skip source or not.\n\n :param source:\n :return:\n '''\n if source.invalid:\n if source.uri and source.type and source.type in (\"deb\", \"deb-src\", \"rpm\", \"rpm-src\"):\n pieces = source.mysplit(source.line)\n if pieces[1].strip()[0] == \"[\":\n options = pieces.pop(1).strip(\"[]\").split()\n if options:\n log.debug(\"Source %s will be included although is marked invalid\", source.uri)\n return False\n return True\n else:\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
get_repo
|
python
|
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
|
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1629-L1701
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def list_repos(**kwargs):\n '''\n Lists all repos in the sources.list (and sources.lists.d) files\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_repos\n salt '*' pkg.list_repos disabled=True\n '''\n _check_apt()\n repos = {}\n sources = sourceslist.SourcesList()\n for source in sources.list:\n if _skip_source(source):\n continue\n repo = {}\n repo['file'] = source.file\n repo['comps'] = getattr(source, 'comps', [])\n repo['disabled'] = source.disabled\n repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules\n repo['dist'] = source.dist\n repo['type'] = source.type\n repo['uri'] = source.uri.rstrip('/')\n repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())\n repo['architectures'] = getattr(source, 'architectures', [])\n repos.setdefault(source.uri, []).append(repo)\n return repos\n",
"def _check_apt():\n '''\n Abort if python-apt is not installed\n '''\n if not HAS_APT:\n raise CommandExecutionError(\n 'Error: \\'python-apt\\' package not installed'\n )\n",
"def _split_repo_str(repo):\n '''\n Return APT source entry as a tuple.\n '''\n split = sourceslist.SourceEntry(repo)\n return split.type, split.architectures, split.uri, split.dist, split.comps\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
del_repo
|
python
|
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
|
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1704-L1814
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def _check_apt():\n '''\n Abort if python-apt is not installed\n '''\n if not HAS_APT:\n raise CommandExecutionError(\n 'Error: \\'python-apt\\' package not installed'\n )\n",
"def _warn_software_properties(repo):\n '''\n Warn of missing python-software-properties package.\n '''\n log.warning('The \\'python-software-properties\\' package is not installed. '\n 'For more accurate support of PPA repositories, you should '\n 'install this package.')\n log.warning('Best guess at ppa format: %s', repo)\n",
"def _split_repo_str(repo):\n '''\n Return APT source entry as a tuple.\n '''\n split = sourceslist.SourceEntry(repo)\n return split.type, split.architectures, split.uri, split.dist, split.comps\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
get_repo_keys
|
python
|
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
|
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1835-L1904
|
[
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
add_repo_key
|
python
|
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
|
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1907-L1975
|
[
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"def get_repo_keys():\n '''\n .. versionadded:: 2017.7.0\n\n List known repo key details.\n\n :return: A dictionary containing the repo keys.\n :rtype: dict\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.get_repo_keys\n '''\n ret = dict()\n repo_keys = list()\n\n # The double usage of '--with-fingerprint' is necessary in order to\n # retrieve the fingerprint of the subkey.\n cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',\n '--with-fingerprint', '--with-colons', '--fixed-list-mode']\n\n cmd_ret = _call_apt(cmd, scope=False)\n\n if cmd_ret['retcode'] != 0:\n log.error(cmd_ret['stderr'])\n return ret\n\n lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]\n\n # Reference for the meaning of each item in the colon-separated\n # record can be found here: https://goo.gl/KIZbvp\n for line in lines:\n items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]\n key_props = dict()\n\n if len(items) < 2:\n log.debug('Skipping line: %s', line)\n continue\n\n if items[0] in ('pub', 'sub'):\n key_props.update({\n 'algorithm': items[3],\n 'bits': items[2],\n 'capability': items[11],\n 'date_creation': items[5],\n 'date_expiration': items[6],\n 'keyid': items[4],\n 'validity': items[1]\n })\n\n if items[0] == 'pub':\n repo_keys.append(key_props)\n else:\n repo_keys[-1]['subkey'] = key_props\n elif items[0] == 'fpr':\n if repo_keys[-1].get('subkey', False):\n repo_keys[-1]['subkey'].update({'fingerprint': items[9]})\n else:\n repo_keys[-1].update({'fingerprint': items[9]})\n elif items[0] == 'uid':\n repo_keys[-1].update({\n 'uid': items[9],\n 'uid_hash': items[7]\n })\n\n for repo_key in repo_keys:\n ret[repo_key['keyid']] = repo_key\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
del_repo_key
|
python
|
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
|
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L1978-L2030
|
[
"def _get_ppa_info_from_launchpad(owner_name, ppa_name):\n '''\n Idea from softwareproperties.ppa.\n Uses urllib2 which sacrifices server cert verification.\n\n This is used as fall-back code or for secure PPAs\n\n :param owner_name:\n :param ppa_name:\n :return:\n '''\n\n lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(\n owner_name, ppa_name)\n request = _Request(lp_url, headers={'Accept': 'application/json'})\n lp_page = _urlopen(request)\n return salt.utils.json.load(lp_page)\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
mod_repo
|
python
|
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
|
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2033-L2362
|
[
"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 warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def get_repo(repo, **kwargs):\n '''\n Display a repo from the sources.list / sources.list.d\n\n The repo passed in needs to be a complete repo entry.\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.get_repo \"myrepo definition\"\n '''\n _check_apt()\n ppa_auth = kwargs.get('ppa_auth', None)\n # we have to be clever about this since the repo definition formats\n # are a bit more \"loose\" than in some other distributions\n if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):\n # This is a PPA definition meaning special handling is needed\n # to derive the name.\n dist = __grains__['lsb_distrib_codename']\n owner_name, ppa_name = repo[4:].split('/')\n if ppa_auth:\n auth_info = '{0}@'.format(ppa_auth)\n repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,\n ppa_name, dist)\n else:\n if HAS_SOFTWAREPROPERTIES:\n try:\n if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):\n repo = softwareproperties.ppa.PPAShortcutHandler(\n repo).expand(dist)[0]\n else:\n repo = softwareproperties.ppa.expand_ppa_line(\n repo,\n dist)[0]\n except NameError as name_error:\n raise CommandExecutionError(\n 'Could not find ppa {0}: {1}'.format(repo, name_error)\n )\n else:\n repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)\n\n repos = list_repos()\n\n if repos:\n try:\n repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)\n if ppa_auth:\n uri_match = re.search('(http[s]?://)(.+)', repo_uri)\n if uri_match:\n if not uri_match.group(2).startswith(ppa_auth):\n repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),\n ppa_auth,\n uri_match.group(2))\n except SyntaxError:\n raise CommandExecutionError(\n 'Error: repo \\'{0}\\' is not a well formatted definition'\n .format(repo)\n )\n\n for source in six.itervalues(repos):\n for sub in source:\n if (sub['type'] == repo_type and\n # strip trailing '/' from repo_uri, it's valid in definition\n # but not valid when compared to persisted source\n sub['uri'].rstrip('/') == repo_uri.rstrip('/') and\n sub['dist'] == repo_dist):\n if not repo_comps:\n return sub\n for comp in repo_comps:\n if comp in sub.get('comps', []):\n return sub\n return {}\n",
"def _get_ppa_info_from_launchpad(owner_name, ppa_name):\n '''\n Idea from softwareproperties.ppa.\n Uses urllib2 which sacrifices server cert verification.\n\n This is used as fall-back code or for secure PPAs\n\n :param owner_name:\n :param ppa_name:\n :return:\n '''\n\n lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(\n owner_name, ppa_name)\n request = _Request(lp_url, headers={'Accept': 'application/json'})\n lp_page = _urlopen(request)\n return salt.utils.json.load(lp_page)\n",
"def _check_apt():\n '''\n Abort if python-apt is not installed\n '''\n if not HAS_APT:\n raise CommandExecutionError(\n 'Error: \\'python-apt\\' package not installed'\n )\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"def _warn_software_properties(repo):\n '''\n Warn of missing python-software-properties package.\n '''\n log.warning('The \\'python-software-properties\\' package is not installed. '\n 'For more accurate support of PPA repositories, you should '\n 'install this package.')\n log.warning('Best guess at ppa format: %s', repo)\n",
"def _split_repo_str(repo):\n '''\n Return APT source entry as a tuple.\n '''\n split = sourceslist.SourceEntry(repo)\n return split.type, split.architectures, split.uri, split.dist, split.comps\n",
"def _consolidate_repo_sources(sources):\n '''\n Consolidate APT sources.\n '''\n if not isinstance(sources, sourceslist.SourcesList):\n raise TypeError(\n '\\'{0}\\' not a \\'{1}\\''.format(\n type(sources),\n sourceslist.SourcesList\n )\n )\n\n consolidated = {}\n delete_files = set()\n base_file = sourceslist.SourceEntry('').file\n\n repos = [s for s in sources.list if not s.invalid]\n\n for repo in repos:\n repo.uri = repo.uri.rstrip('/')\n # future lint: disable=blacklisted-function\n key = str((getattr(repo, 'architectures', []),\n repo.disabled, repo.type, repo.uri, repo.dist))\n # future lint: enable=blacklisted-function\n if key in consolidated:\n combined = consolidated[key]\n combined_comps = set(repo.comps).union(set(combined.comps))\n consolidated[key].comps = list(combined_comps)\n else:\n consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))\n\n if repo.file != base_file:\n delete_files.add(repo.file)\n\n sources.list = list(consolidated.values())\n sources.save()\n for file_ in delete_files:\n try:\n os.remove(file_)\n except OSError:\n pass\n return sources\n",
"def _get_http_proxy_url():\n '''\n Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port\n config values are set.\n\n Returns a string.\n '''\n http_proxy_url = ''\n host = __salt__['config.option']('proxy_host')\n port = __salt__['config.option']('proxy_port')\n username = __salt__['config.option']('proxy_username')\n password = __salt__['config.option']('proxy_password')\n\n # Set http_proxy_url for use in various internet facing actions...eg apt-key adv\n if host and port:\n if username and password:\n http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(\n username,\n password,\n host,\n port\n )\n else:\n http_proxy_url = 'http://{0}:{1}'.format(\n host,\n port\n )\n\n return http_proxy_url\n",
"def combine_comments(comments):\n '''\n Given a list of comments, or a comment submitted as a string, return a\n single line of text containing all of the comments.\n '''\n if isinstance(comments, list):\n for idx in range(len(comments)):\n if not isinstance(comments[idx], six.string_types):\n comments[idx] = six.text_type(comments[idx])\n else:\n if not isinstance(comments, six.string_types):\n comments = [six.text_type(comments)]\n else:\n comments = [comments]\n return ' '.join(comments).strip()\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
expand_repo_def
|
python
|
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
|
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2399-L2452
|
[
"def _check_apt():\n '''\n Abort if python-apt is not installed\n '''\n if not HAS_APT:\n raise CommandExecutionError(\n 'Error: \\'python-apt\\' package not installed'\n )\n",
"def strip_uri(repo):\n '''\n Remove the trailing slash from the URI in a repo definition\n '''\n splits = repo.split()\n for idx in range(len(splits)):\n if any(splits[idx].startswith(x)\n for x in ('http://', 'https://', 'ftp://')):\n splits[idx] = splits[idx].rstrip('/')\n return ' '.join(splits)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_parse_selections
|
python
|
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
|
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2455-L2470
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
get_selections
|
python
|
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
|
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2473-L2507
|
[
"def _parse_selections(dpkgselection):\n '''\n Parses the format from ``dpkg --get-selections`` and return a format that\n pkg.get_selections and pkg.set_selections work with.\n '''\n ret = {}\n if isinstance(dpkgselection, six.string_types):\n dpkgselection = dpkgselection.split('\\n')\n for line in dpkgselection:\n if line:\n _pkg, _state = line.split()\n if _state in ret:\n ret[_state].append(_pkg)\n else:\n ret[_state] = [_pkg]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
set_selections
|
python
|
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
|
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2516-L2618
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\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 safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"def get_selections(pattern=None, state=None):\n '''\n View package state from the dpkg database.\n\n Returns a dict of dicts containing the state, and package names:\n\n .. code-block:: python\n\n {'<host>':\n {'<state>': ['pkg1',\n ...\n ]\n },\n ...\n }\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.get_selections\n salt '*' pkg.get_selections 'python-*'\n salt '*' pkg.get_selections state=hold\n salt '*' pkg.get_selections 'openssh*' state=hold\n '''\n ret = {}\n cmd = ['dpkg', '--get-selections']\n cmd.append(pattern if pattern else '*')\n stdout = __salt__['cmd.run_stdout'](cmd,\n output_loglevel='trace',\n python_shell=False)\n ret = _parse_selections(stdout)\n if state:\n return {state: ret.get(state, [])}\n return ret\n",
"def _parse_selections(dpkgselection):\n '''\n Parses the format from ``dpkg --get-selections`` and return a format that\n pkg.get_selections and pkg.set_selections work with.\n '''\n ret = {}\n if isinstance(dpkgselection, six.string_types):\n dpkgselection = dpkgselection.split('\\n')\n for line in dpkgselection:\n if line:\n _pkg, _state = line.split()\n if _state in ret:\n ret[_state].append(_pkg)\n else:\n ret[_state] = [_pkg]\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_resolve_deps
|
python
|
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
|
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2621-L2663
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
show
|
python
|
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
|
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2701-L2782
|
[
"def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n",
"def 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 split_input(val, mapper=None):\n '''\n Take an input value and split it into a list, returning the resulting list\n '''\n if mapper is None:\n mapper = lambda x: x\n if isinstance(val, list):\n return list(map(mapper, val))\n try:\n return list(map(mapper, [x.strip() for x in val.split(',')]))\n except AttributeError:\n return list(map(mapper, [x.strip() for x in six.text_type(val).split(',')]))\n",
"def refresh_db(cache_valid_time=0, failhard=False, **kwargs):\n '''\n Updates the APT database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n - ``None``: Database already up-to-date\n\n cache_valid_time\n\n .. versionadded:: 2016.11.0\n\n Skip refreshing the package database if refresh has already occurred within\n <value> seconds\n\n failhard\n\n If False, return results of Err lines as ``False`` for the package database that\n encountered the error.\n If True, raise an error with a list of the package databases that encountered\n errors.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n failhard = salt.utils.data.is_true(failhard)\n ret = {}\n error_repos = list()\n\n if cache_valid_time:\n try:\n latest_update = os.stat(APT_LISTS_PATH).st_mtime\n now = time.time()\n log.debug(\"now: %s, last update time: %s, expire after: %s seconds\", now, latest_update, cache_valid_time)\n if latest_update + cache_valid_time > now:\n return ret\n except TypeError as exp:\n log.warning(\"expected integer for cache_valid_time parameter, failed with: %s\", exp)\n except IOError as exp:\n log.warning(\"could not stat cache directory due to: %s\", exp)\n\n call = _call_apt(['apt-get', '-q', 'update'], scope=False)\n if call['retcode'] != 0:\n comment = ''\n if 'stderr' in call:\n comment += call['stderr']\n\n raise CommandExecutionError(comment)\n else:\n out = call['stdout']\n\n for line in out.splitlines():\n cols = line.split()\n if not cols:\n continue\n ident = ' '.join(cols[1:])\n if 'Get' in cols[0]:\n # Strip filesize from end of line\n ident = re.sub(r' \\[.+B\\]$', '', ident)\n ret[ident] = True\n elif 'Ign' in cols[0]:\n ret[ident] = False\n elif 'Hit' in cols[0]:\n ret[ident] = None\n elif 'Err' in cols[0]:\n ret[ident] = False\n error_repos.append(ident)\n\n if failhard and error_repos:\n raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))\n\n return ret\n",
"def _call_apt(args, scope=True, **kwargs):\n '''\n Call apt* utilities.\n '''\n cmd = []\n if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):\n cmd.extend(['systemd-run', '--scope'])\n cmd.extend(args)\n\n params = {'output_loglevel': 'trace',\n 'python_shell': False,\n 'env': salt.utils.environment.get_module_environment(globals())}\n params.update(kwargs)\n\n return __salt__['cmd.run_all'](cmd, **params)\n",
"def invalid_kwargs(invalid_kwargs, raise_exc=True):\n '''\n Raise a SaltInvocationError if invalid_kwargs is non-empty\n '''\n if invalid_kwargs:\n if isinstance(invalid_kwargs, dict):\n new_invalid = [\n '{0}={1}'.format(x, y)\n for x, y in six.iteritems(invalid_kwargs)\n ]\n invalid_kwargs = new_invalid\n msg = (\n 'The following keyword arguments are not valid: {0}'\n .format(', '.join(invalid_kwargs))\n )\n if raise_exc:\n raise SaltInvocationError(msg)\n else:\n return msg\n",
"def _add(ret, pkginfo):\n name = pkginfo.pop('Package', None)\n version = pkginfo.pop('Version', None)\n if name is not None and version is not None:\n ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)\n",
"def _check_filter(key):\n key = key.lower()\n return True if key in ('package', 'version') or not filter_ \\\n else key in filter_\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
info_installed
|
python
|
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
|
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2785-L2853
|
[
"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 invalid_kwargs(invalid_kwargs, raise_exc=True):\n '''\n Raise a SaltInvocationError if invalid_kwargs is non-empty\n '''\n if invalid_kwargs:\n if isinstance(invalid_kwargs, dict):\n new_invalid = [\n '{0}={1}'.format(x, y)\n for x, y in six.iteritems(invalid_kwargs)\n ]\n invalid_kwargs = new_invalid\n msg = (\n 'The following keyword arguments are not valid: {0}'\n .format(', '.join(invalid_kwargs))\n )\n if raise_exc:\n raise SaltInvocationError(msg)\n else:\n return msg\n"
] |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
saltstack/salt
|
salt/modules/aptpkg.py
|
_get_http_proxy_url
|
python
|
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
username = __salt__['config.option']('proxy_username')
password = __salt__['config.option']('proxy_password')
# Set http_proxy_url for use in various internet facing actions...eg apt-key adv
if host and port:
if username and password:
http_proxy_url = 'http://{0}:{1}@{2}:{3}'.format(
username,
password,
host,
port
)
else:
http_proxy_url = 'http://{0}:{1}'.format(
host,
port
)
return http_proxy_url
|
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptpkg.py#L2856-L2884
| null |
# -*- coding: utf-8 -*-
'''
Support for APT (Advanced Packaging Tool)
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``python-apt`` package must be installed.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import copy
import os
import re
import logging
import time
# Import third party libs
# pylint: disable=no-name-in-module,import-error,redefined-builtin
from salt.ext import six
from salt.ext.six.moves.urllib.error import HTTPError
from salt.ext.six.moves.urllib.request import Request as _Request, urlopen as _urlopen
# pylint: enable=no-name-in-module,import-error,redefined-builtin
# Import salt libs
import salt.config
import salt.syspaths
from salt.modules.cmdmod import _parse_env
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
import salt.utils.environment
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
# pylint: disable=import-error
try:
import apt.cache
import apt.debfile
from aptsources import sourceslist
HAS_APT = True
except ImportError:
HAS_APT = False
try:
import apt_pkg
HAS_APTPKG = True
except ImportError:
HAS_APTPKG = False
try:
import softwareproperties.ppa
HAS_SOFTWAREPROPERTIES = True
except ImportError:
HAS_SOFTWAREPROPERTIES = False
# pylint: enable=import-error
APT_LISTS_PATH = "/var/lib/apt/lists"
# Source format for urllib fallback on PPA handling
LP_SRC_FORMAT = 'deb http://ppa.launchpad.net/{0}/{1}/ubuntu {2} main'
LP_PVT_SRC_FORMAT = 'deb https://{0}private-ppa.launchpad.net/{1}/{2}/ubuntu' \
' {3} main'
_MODIFY_OK = frozenset(['uri', 'comps', 'architectures', 'disabled',
'file', 'dist'])
DPKG_ENV_VARS = {
'APT_LISTBUGS_FRONTEND': 'none',
'APT_LISTCHANGES_FRONTEND': 'none',
'DEBIAN_FRONTEND': 'noninteractive',
'UCF_FORCE_CONFFOLD': '1',
}
if six.PY2:
# Ensure no unicode in env vars on PY2, as it causes problems with
# subprocess.Popen()
DPKG_ENV_VARS = salt.utils.data.encode(DPKG_ENV_VARS)
# Define the module's virtual name
__virtualname__ = 'pkg'
def __virtual__():
'''
Confirm this module is on a Debian-based system
'''
# If your minion is running an OS which is Debian-based but does not have
# an "os_family" grain of Debian, then the proper fix is NOT to check for
# the minion's "os_family" grain here in the __virtual__. The correct fix
# is to add the value from the minion's "os" grain to the _OS_FAMILY_MAP
# dict in salt/grains/core.py, so that we assign the correct "os_family"
# grain to the minion.
if __grains__.get('os_family') == 'Debian':
return __virtualname__
return False, 'The pkg module could not be loaded: unsupported OS family'
def __init__(opts):
'''
For Debian and derivative systems, set up
a few env variables to keep apt happy and
non-interactive.
'''
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
def _get_ppa_info_from_launchpad(owner_name, ppa_name):
'''
Idea from softwareproperties.ppa.
Uses urllib2 which sacrifices server cert verification.
This is used as fall-back code or for secure PPAs
:param owner_name:
:param ppa_name:
:return:
'''
lp_url = 'https://launchpad.net/api/1.0/~{0}/+archive/{1}'.format(
owner_name, ppa_name)
request = _Request(lp_url, headers={'Accept': 'application/json'})
lp_page = _urlopen(request)
return salt.utils.json.load(lp_page)
def _reconstruct_ppa_name(owner_name, ppa_name):
'''
Stringify PPA name from args.
'''
return 'ppa:{0}/{1}'.format(owner_name, ppa_name)
def _check_apt():
'''
Abort if python-apt is not installed
'''
if not HAS_APT:
raise CommandExecutionError(
'Error: \'python-apt\' package not installed'
)
def _call_apt(args, scope=True, **kwargs):
'''
Call apt* utilities.
'''
cmd = []
if scope and salt.utils.systemd.has_scope(__context__) and __salt__['config.get']('systemd.scope', True):
cmd.extend(['systemd-run', '--scope'])
cmd.extend(args)
params = {'output_loglevel': 'trace',
'python_shell': False,
'env': salt.utils.environment.get_module_environment(globals())}
params.update(kwargs)
return __salt__['cmd.run_all'](cmd, **params)
def _warn_software_properties(repo):
'''
Warn of missing python-software-properties package.
'''
log.warning('The \'python-software-properties\' package is not installed. '
'For more accurate support of PPA repositories, you should '
'install this package.')
log.warning('Best guess at ppa format: %s', repo)
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
show_installed = salt.utils.data.is_true(kwargs.pop('show_installed', False))
if 'repo' in kwargs:
raise SaltInvocationError(
'The \'repo\' argument is invalid, use \'fromrepo\' instead'
)
fromrepo = kwargs.pop('fromrepo', None)
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if not names:
return ''
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ''
pkgs = list_pkgs(versions_as_list=True)
repo = ['-o', 'APT::Default-Release={0}'.format(fromrepo)] \
if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ['apt-cache', '-q', 'policy', name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ''
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if 'Candidate' in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == '(none)':
candidate = ''
break
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
(salt.utils.versions.compare(ver1=x,
oper='>=',
ver2=candidate,
cmp_func=version_cmp)
for x in installed)
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(latest_version, 'available_version')
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
'''
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug("now: %s, last update time: %s, expire after: %s seconds", now, latest_update, cache_valid_time)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning("expected integer for cache_valid_time parameter, failed with: %s", exp)
except IOError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(['apt-get', '-q', 'update'], scope=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = ' '.join(cols[1:])
if 'Get' in cols[0]:
# Strip filesize from end of line
ident = re.sub(r' \[.+B\]$', '', ident)
ret[ident] = True
elif 'Ign' in cols[0]:
ret[ident] = False
elif 'Hit' in cols[0]:
ret[ident] = None
elif 'Err' in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError('Error getting repos: {0}'.format(', '.join(error_repos)))
return ret
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
ignore_epoch=False,
**kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of DEB packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if 'version' in kwargs and kwargs['version']:
_refresh_db = False
_latest_version = latest_version(name,
refresh=False,
show_installed=True)
_version = kwargs.get('version')
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(six.iterkeys(pkg))
_latest_version = latest_version(_name,
refresh=False,
show_installed=True)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__['debconf.set_file'](debconf)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get('repo', '')
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == 'repository':
pkg_params_items = list(six.iteritems(pkg_params))
has_comparison = [x for x, y in pkg_params_items
if y is not None
and (y.startswith('<') or y.startswith('>'))]
_available = list_repo_pkgs(*has_comparison, byrepo=False, **kwargs) \
if has_comparison else {}
# Build command prefix
cmd_prefix.extend(['apt-get', '-q', '-y'])
if kwargs.get('force_yes', False):
cmd_prefix.append('--force-yes')
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confnew'])
else:
cmd_prefix.extend(['-o', 'DPkg::Options::=--force-confold'])
cmd_prefix += ['-o', 'DPkg::Options::=--force-confdef']
if 'install_recommends' in kwargs:
if not kwargs['install_recommends']:
cmd_prefix.append('--no-install-recommends')
else:
cmd_prefix.append('--install-recommends')
if 'only_upgrade' in kwargs and kwargs['only_upgrade']:
cmd_prefix.append('--only-upgrade')
if skip_verify:
cmd_prefix.append('--allow-unauthenticated')
if fromrepo:
cmd_prefix.extend(['-t', fromrepo])
cmd_prefix.append('install')
else:
pkg_params_items = []
for pkg_source in pkg_params:
if 'lowpkg.bin_pkg_info' in __salt__:
deb_info = __salt__['lowpkg.bin_pkg_info'](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
'pkg.install: Unable to get deb information for %s. '
'Version comparisons will be unavailable.', pkg_source
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info['name'], pkg_source, deb_info['version']]
)
# Build command prefix
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
cmd_prefix.extend(['dpkg', '-i', '--force-confnew'])
else:
cmd_prefix.extend(['dpkg', '-i', '--force-confold'])
if skip_verify:
cmd_prefix.append('--force-bad-verify')
if HAS_APT:
_resolve_deps(name, pkg_params, **kwargs)
for pkg_item_list in pkg_params_items:
if pkg_type == 'repository':
pkgname, version_num = pkg_item_list
if name \
and pkgs is None \
and kwargs.get('version') \
and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == 'repository':
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == 'repository':
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip('=')
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
'No version matching \'{0}{1}\' could be found '
'(available: {2})'.format(
pkgname,
version_num,
', '.join(candidates) if candidates else None
)
)
continue
else:
version_num = target
pkgstr = '{0}={1}'.format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, '')
if reinstall and cver \
and salt.utils.versions.compare(ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info('Targeting repo \'%s\'', fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == 'repository' and '--force-yes' not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, '--force-yes')
cmd.extend(downgrade)
cmds.append(cmd)
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append('--reinstall')
cmd.extend([x for x in six.itervalues(to_reinstall)])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
hold_pkgs = get_selections(state='hold').get('hold', [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the pacakges we are trying to install.
targeted_names = [x.split('=')[0] for x in all_pkgs]
to_unhold = [x for x in hold_pkgs if x in targeted_names]
if to_unhold:
unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out['retcode'] != 0 and out['stderr']:
errors.append(out['stderr'])
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
if to_unhold:
hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == 'purge':
targets.extend([x for x in pkg_params if x in old_removed])
if not targets:
return {}
cmd = ['apt-get', '-q', '-y', action]
cmd.extend(targets)
env = _parse_env(kwargs.get('env'))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out['retcode'] != 0 and out['stderr']:
errors = [out['stderr']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
new_removed = list_pkgs(removed=True)
changes = salt.utils.data.compare_dicts(old, new)
if action == 'purge':
ret = {
'removed': salt.utils.data.compare_dicts(old_removed, new_removed),
'installed': changes
}
else:
ret = changes
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
return ret
def autoremove(list_only=False, purge=False):
'''
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
'''
cmd = []
if list_only:
ret = []
cmd.extend(['apt-get', '--assume-no'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
out = _call_apt(cmd, ignore_retcode=True)['stdout']
found = False
for line in out.splitlines():
if found is True:
if line.startswith(' '):
ret.extend(line.split())
else:
found = False
elif 'The following packages will be REMOVED:' in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(['apt-get', '--assume-yes'])
if purge:
cmd.append('--purge')
cmd.append('autoremove')
_call_apt(cmd, ignore_retcode=True)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
return _uninstall(action='remove', name=name, pkgs=pkgs, **kwargs)
def purge(name=None, pkgs=None, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages via ``apt-get purge`` along with all configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs)
def upgrade(refresh=True, dist_upgrade=False, **kwargs):
'''
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Upgrades all packages via ``apt-get upgrade`` or ``apt-get dist-upgrade``
if ``dist_upgrade`` is ``True``.
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
dist_upgrade
Whether to perform the upgrade using dist-upgrade vs upgrade. Default
is to use upgrade.
.. versionadded:: 2014.7.0
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
download_only
Only download the packages, don't unpack or install them
.. versionadded:: 2018.3.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
old = list_pkgs()
if 'force_conf_new' in kwargs and kwargs['force_conf_new']:
force_conf = '--force-confnew'
else:
force_conf = '--force-confold'
cmd = ['apt-get', '-q', '-y', '-o', 'DPkg::Options::={0}'.format(force_conf),
'-o', 'DPkg::Options::=--force-confdef']
if kwargs.get('force_yes', False):
cmd.append('--force-yes')
if kwargs.get('skip_verify', False):
cmd.append('--allow-unauthenticated')
if kwargs.get('download_only', False):
cmd.append('--download-only')
cmd.append('dist-upgrade' if dist_upgrade else 'upgrade')
result = _call_apt(cmd, env=DPKG_ENV_VARS.copy())
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'changes': ret, 'result': result}
)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target, state='hold')
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif not salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = set_selections(selection={'hold': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
.. versionadded:: 2014.7.0
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to unhold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = get_selections(pattern=target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif salt.utils.data.is_true(state.get('hold', False)):
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set not to be '
'held.'.format(target))
else:
result = set_selections(selection={'install': [target]})
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def list_pkgs(versions_as_list=False,
removed=False,
purge_desired=False,
**kwargs): # pylint: disable=W0613
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
removed
If ``True``, then only packages which have been removed (but not
purged) will be returned.
purge_desired
If ``True``, then only packages which have been marked to be purged,
but can't be purged due to their status as dependencies for other
installed packages, will be returned. Note that these packages will
appear in installed
.. versionchanged:: 2014.1.1
Packages in this state now correctly show up in the output of this
function.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
removed = salt.utils.data.is_true(removed)
purge_desired = salt.utils.data.is_true(purge_desired)
if 'pkg.list_pkgs' in __context__:
if removed:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['removed'])
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {'installed': {}, 'removed': {}, 'purge_desired': {}}
cmd = ['dpkg-query', '--showformat',
'${Status} ${Package} ${Version} ${Architecture}\n', '-W']
out = __salt__['cmd.run_stdout'](
cmd,
output_loglevel='trace',
python_shell=False)
# Typical lines of output:
# install ok installed zsh 4.3.17-1ubuntu1 amd64
# deinstall ok config-files mc 3:4.8.1-2ubuntu1 amd64
for line in out.splitlines():
cols = line.split()
try:
linetype, status, name, version_num, arch = \
[cols[x] for x in (0, 2, 3, 4, 5)]
except (ValueError, IndexError):
continue
if __grains__.get('cpuarch', '') == 'x86_64':
osarch = __grains__.get('osarch', '')
if arch != 'all' and osarch == 'amd64' and osarch != arch:
name += ':{0}'.format(arch)
if cols:
if ('install' in linetype or 'hold' in linetype) and \
'installed' in status:
__salt__['pkg_resource.add_pkg'](ret['installed'],
name,
version_num)
elif 'deinstall' in linetype:
__salt__['pkg_resource.add_pkg'](ret['removed'],
name,
version_num)
elif 'purge' in linetype and status == 'installed':
__salt__['pkg_resource.add_pkg'](ret['purge_desired'],
name,
version_num)
for pkglist_type in ('installed', 'removed', 'purge_desired'):
__salt__['pkg_resource.sort_pkglist'](ret[pkglist_type])
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if removed:
ret = ret['removed']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs']['purge_desired'])
if not purge_desired:
ret.update(__context__['pkg.list_pkgs']['installed'])
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
def _get_upgradable(dist_upgrade=True, **kwargs):
'''
Utility function to get upgradable packages
Sample return data:
{ 'pkgname': '1.2.3-45', ... }
'''
cmd = ['apt-get', '--just-print']
if dist_upgrade:
cmd.append('dist-upgrade')
else:
cmd.append('upgrade')
try:
cmd.extend(['-o', 'APT::Default-Release={0}'.format(kwargs['fromrepo'])])
except KeyError:
pass
call = _call_apt(cmd)
if call['retcode'] != 0:
msg = 'Failed to get upgrades'
for key in ('stderr', 'stdout'):
if call[key]:
msg += ': ' + call[key]
break
raise CommandExecutionError(msg)
else:
out = call['stdout']
# rexp parses lines that look like the following:
# Conf libxfont1 (1:1.4.5-1 Debian:testing [i386])
rexp = re.compile('(?m)^Conf '
'([^ ]+) ' # Package name
r'\(([^ ]+)') # Version
keys = ['name', 'version']
_get = lambda l, k: l[keys.index(k)]
upgrades = rexp.findall(out)
ret = {}
for line in upgrades:
name = _get(line, 'name')
version_num = _get(line, 'version')
ret[name] = version_num
return ret
def list_upgrades(refresh=True, dist_upgrade=True, **kwargs):
'''
List all available package upgrades.
refresh
Whether to refresh the package database before listing upgrades.
Default: True.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
dist_upgrade
Whether to list the upgrades using dist-upgrade vs upgrade. Default is
to use dist-upgrade.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
cache_valid_time = kwargs.pop('cache_valid_time', 0)
if salt.utils.data.is_true(refresh):
refresh_db(cache_valid_time)
return _get_upgradable(dist_upgrade, **kwargs)
def upgrade_available(name, **kwargs):
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0ubuntu1' '0.2.4.1-0ubuntu1'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] \
if ignore_epoch else six.text_type(x)
# both apt_pkg.version_compare and _cmd_quote need string arguments.
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
# if we have apt_pkg, this will be quickier this way
# and also do not rely on shell.
if HAS_APTPKG:
try:
# the apt_pkg module needs to be manually initialized
apt_pkg.init_system()
# if there is a difference in versions, apt_pkg.version_compare will
# return an int representing the difference in minor versions, or
# 1/-1 if the difference is smaller than minor versions. normalize
# to -1, 0 or 1.
try:
ret = apt_pkg.version_compare(pkg1, pkg2)
except TypeError:
ret = apt_pkg.version_compare(six.text_type(pkg1), six.text_type(pkg2))
return 1 if ret > 0 else -1 if ret < 0 else 0
except Exception:
# Try to use shell version in case of errors w/python bindings
pass
try:
for oper, ret in (('lt', -1), ('eq', 0), ('gt', 1)):
cmd = ['dpkg', '--compare-versions', pkg1, oper, pkg2]
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True)
if retcode == 0:
return ret
except Exception as exc:
log.error(exc)
return None
def _split_repo_str(repo):
'''
Return APT source entry as a tuple.
'''
split = sourceslist.SourceEntry(repo)
return split.type, split.architectures, split.uri, split.dist, split.comps
def _consolidate_repo_sources(sources):
'''
Consolidate APT sources.
'''
if not isinstance(sources, sourceslist.SourcesList):
raise TypeError(
'\'{0}\' not a \'{1}\''.format(
type(sources),
sourceslist.SourcesList
)
)
consolidated = {}
delete_files = set()
base_file = sourceslist.SourceEntry('').file
repos = [s for s in sources.list if not s.invalid]
for repo in repos:
repo.uri = repo.uri.rstrip('/')
# future lint: disable=blacklisted-function
key = str((getattr(repo, 'architectures', []),
repo.disabled, repo.type, repo.uri, repo.dist))
# future lint: enable=blacklisted-function
if key in consolidated:
combined = consolidated[key]
combined_comps = set(repo.comps).union(set(combined.comps))
consolidated[key].comps = list(combined_comps)
else:
consolidated[key] = sourceslist.SourceEntry(salt.utils.pkg.deb.strip_uri(repo.line))
if repo.file != base_file:
delete_files.add(repo.file)
sources.list = list(consolidated.values())
sources.save()
for file_ in delete_files:
try:
os.remove(file_)
except OSError:
pass
return sources
def list_repo_pkgs(*args, **kwargs): # pylint: disable=unused-import
'''
.. versionadded:: 2017.7.0
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. For example:
.. code-block:: python
{
'bash': ['4.3-14ubuntu1.1',
'4.3-14ubuntu1'],
'nginx': ['1.10.0-0ubuntu0.16.04.4',
'1.9.15-0ubuntu1']
}
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
'''
if args:
# Get only information about packages in args
cmd = ['apt-cache', 'show'] + [arg for arg in args]
else:
# Get information about all available packages
cmd = ['apt-cache', 'dump']
out = _call_apt(cmd, scope=False, ignore_retcode=True)
ret = {}
pkg_name = None
skip_pkg = False
new_pkg = re.compile('^Package: (.+)')
for line in salt.utils.itertools.split(out['stdout'], '\n'):
if not line.strip():
continue
try:
cur_pkg = new_pkg.match(line).group(1)
except AttributeError:
pass
else:
if cur_pkg != pkg_name:
pkg_name = cur_pkg
continue
comps = line.strip().split(None, 1)
if comps[0] == 'Version:':
ret.setdefault(pkg_name, []).append(comps[1])
return ret
def _skip_source(source):
'''
Decide to skip source or not.
:param source:
:return:
'''
if source.invalid:
if source.uri and source.type and source.type in ("deb", "deb-src", "rpm", "rpm-src"):
pieces = source.mysplit(source.line)
if pieces[1].strip()[0] == "[":
options = pieces.pop(1).strip("[]").split()
if options:
log.debug("Source %s will be included although is marked invalid", source.uri)
return False
return True
else:
return True
return False
def list_repos(**kwargs):
'''
Lists all repos in the sources.list (and sources.lists.d) files
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
salt '*' pkg.list_repos disabled=True
'''
_check_apt()
repos = {}
sources = sourceslist.SourcesList()
for source in sources.list:
if _skip_source(source):
continue
repo = {}
repo['file'] = source.file
repo['comps'] = getattr(source, 'comps', [])
repo['disabled'] = source.disabled
repo['enabled'] = not repo['disabled'] # This is for compatibility with the other modules
repo['dist'] = source.dist
repo['type'] = source.type
repo['uri'] = source.uri.rstrip('/')
repo['line'] = salt.utils.pkg.deb.strip_uri(source.line.strip())
repo['architectures'] = getattr(source, 'architectures', [])
repos.setdefault(source.uri, []).append(repo)
return repos
def get_repo(repo, **kwargs):
'''
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
'''
_check_apt()
ppa_auth = kwargs.get('ppa_auth', None)
# we have to be clever about this since the repo definition formats
# are a bit more "loose" than in some other distributions
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/')
if ppa_auth:
auth_info = '{0}@'.format(ppa_auth)
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name,
ppa_name, dist)
else:
if HAS_SOFTWAREPROPERTIES:
try:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(
repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(
repo,
dist)[0]
except NameError as name_error:
raise CommandExecutionError(
'Could not find ppa {0}: {1}'.format(repo, name_error)
)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
repos = list_repos()
if repos:
try:
repo_type, repo_architectures, repo_uri, repo_dist, repo_comps = _split_repo_str(repo)
if ppa_auth:
uri_match = re.search('(http[s]?://)(.+)', repo_uri)
if uri_match:
if not uri_match.group(2).startswith(ppa_auth):
repo_uri = '{0}{1}@{2}'.format(uri_match.group(1),
ppa_auth,
uri_match.group(2))
except SyntaxError:
raise CommandExecutionError(
'Error: repo \'{0}\' is not a well formatted definition'
.format(repo)
)
for source in six.itervalues(repos):
for sub in source:
if (sub['type'] == repo_type and
# strip trailing '/' from repo_uri, it's valid in definition
# but not valid when compared to persisted source
sub['uri'].rstrip('/') == repo_uri.rstrip('/') and
sub['dist'] == repo_dist):
if not repo_comps:
return sub
for comp in repo_comps:
if comp in sub.get('comps', []):
return sub
return {}
def del_repo(repo, **kwargs):
'''
Delete a repo from the sources.list / sources.list.d
If the .list file is in the sources.list.d directory
and the file that the repo exists in does not contain any other
repo configuration, the file itself will be deleted.
The repo passed in must be a fully formed repository definition
string.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo "myrepo definition"
'''
_check_apt()
is_ppa = False
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# This is a PPA definition meaning special handling is needed
# to derive the name.
is_ppa = True
dist = __grains__['lsb_distrib_codename']
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
owner_name, ppa_name = repo[4:].split('/')
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, dist, owner_name,
ppa_name)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
sources = sourceslist.SourcesList()
repos = [s for s in sources.list if not s.invalid]
if repos:
deleted_from = dict()
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SaltInvocationError(
'Error: repo \'{0}\' not a well formatted definition'
.format(repo)
)
for source in repos:
if (source.type == repo_type
and source.architectures == repo_architectures
and source.uri == repo_uri
and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
# PPAs are special and can add deb-src where expand_ppa_line
# doesn't always reflect this. Lets just cleanup here for good
# measure
if (is_ppa and repo_type == 'deb' and source.type == 'deb-src' and
source.uri == repo_uri and source.dist == repo_dist):
s_comps = set(source.comps)
r_comps = set(repo_comps)
if s_comps.intersection(r_comps):
deleted_from[source.file] = 0
source.comps = list(s_comps.difference(r_comps))
if not source.comps:
try:
sources.remove(source)
except ValueError:
pass
sources.save()
if deleted_from:
ret = ''
for source in sources:
if source.file in deleted_from:
deleted_from[source.file] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 0 and 'sources.list.d/' in repo_file:
if os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
# explicit refresh after a repo is deleted
refresh_db()
return ret
raise CommandExecutionError(
'Repo {0} doesn\'t exist in the sources.list(s)'.format(repo)
)
def _convert_if_int(value):
'''
.. versionadded:: 2017.7.0
Convert to an int if necessary.
:param str value: The value to check/convert.
:return: The converted or passed value.
:rtype: bool|int|str
'''
try:
value = int(str(value)) # future lint: disable=blacklisted-function
except ValueError:
pass
return value
def get_repo_keys():
'''
.. versionadded:: 2017.7.0
List known repo key details.
:return: A dictionary containing the repo keys.
:rtype: dict
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo_keys
'''
ret = dict()
repo_keys = list()
# The double usage of '--with-fingerprint' is necessary in order to
# retrieve the fingerprint of the subkey.
cmd = ['apt-key', 'adv', '--batch', '--list-public-keys', '--with-fingerprint',
'--with-fingerprint', '--with-colons', '--fixed-list-mode']
cmd_ret = _call_apt(cmd, scope=False)
if cmd_ret['retcode'] != 0:
log.error(cmd_ret['stderr'])
return ret
lines = [line for line in cmd_ret['stdout'].splitlines() if line.strip()]
# Reference for the meaning of each item in the colon-separated
# record can be found here: https://goo.gl/KIZbvp
for line in lines:
items = [_convert_if_int(item.strip()) if item.strip() else None for item in line.split(':')]
key_props = dict()
if len(items) < 2:
log.debug('Skipping line: %s', line)
continue
if items[0] in ('pub', 'sub'):
key_props.update({
'algorithm': items[3],
'bits': items[2],
'capability': items[11],
'date_creation': items[5],
'date_expiration': items[6],
'keyid': items[4],
'validity': items[1]
})
if items[0] == 'pub':
repo_keys.append(key_props)
else:
repo_keys[-1]['subkey'] = key_props
elif items[0] == 'fpr':
if repo_keys[-1].get('subkey', False):
repo_keys[-1]['subkey'].update({'fingerprint': items[9]})
else:
repo_keys[-1].update({'fingerprint': items[9]})
elif items[0] == 'uid':
repo_keys[-1].update({
'uid': items[9],
'uid_hash': items[7]
})
for repo_key in repo_keys:
ret[repo_key['keyid']] = repo_key
return ret
def add_repo_key(path=None, text=None, keyserver=None, keyid=None, saltenv='base'):
'''
.. versionadded:: 2017.7.0
Add a repo key using ``apt-key add``.
:param str path: The path of the key file to import.
:param str text: The key data to import, in string form.
:param str keyserver: The server to download the repo key specified by the keyid.
:param str keyid: The key id of the repo key to add.
:param str saltenv: The environment the key file resides in.
:return: A boolean representing whether the repo key was added.
:rtype: bool
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo_key 'salt://apt/sources/test.key'
salt '*' pkg.add_repo_key text="'$KEY1'"
salt '*' pkg.add_repo_key keyserver='keyserver.example' keyid='0000AAAA'
'''
cmd = ['apt-key']
kwargs = {}
current_repo_keys = get_repo_keys()
if path:
cached_source_path = __salt__['cp.cache_file'](path, saltenv)
if not cached_source_path:
log.error('Unable to get cached copy of file: %s', path)
return False
cmd.extend(['add', cached_source_path])
elif text:
log.debug('Received value: %s', text)
cmd.extend(['add', '-'])
kwargs.update({'stdin': text})
elif keyserver:
if not keyid:
error_msg = 'No keyid or keyid too short for keyserver: {0}'.format(keyserver)
raise SaltInvocationError(error_msg)
cmd.extend(['adv', '--batch', '--keyserver', keyserver, '--recv', keyid])
elif keyid:
error_msg = 'No keyserver specified for keyid: {0}'.format(keyid)
raise SaltInvocationError(error_msg)
else:
raise TypeError('{0}() takes at least 1 argument (0 given)'.format(add_repo_key.__name__))
# If the keyid is provided or determined, check it against the existing
# repo key ids to determine whether it needs to be imported.
if keyid:
for current_keyid in current_repo_keys:
if current_keyid[-(len(keyid)):] == keyid:
log.debug("The keyid '%s' already present: %s", keyid, current_keyid)
return True
cmd_ret = _call_apt(cmd, **kwargs)
if cmd_ret['retcode'] == 0:
return True
log.error('Unable to add repo key: %s', cmd_ret['stderr'])
return False
def del_repo_key(name=None, **kwargs):
'''
.. versionadded:: 2015.8.0
Remove a repo key using ``apt-key del``
name
Repo from which to remove the key. Unnecessary if ``keyid`` is passed.
keyid
The KeyID of the GPG key to remove
keyid_ppa : False
If set to ``True``, the repo's GPG key ID will be looked up from
ppa.launchpad.net and removed.
.. note::
Setting this option to ``True`` requires that the ``name`` param
also be passed.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo_key keyid=0123ABCD
salt '*' pkg.del_repo_key name='ppa:foo/bar' keyid_ppa=True
'''
if kwargs.get('keyid_ppa', False):
if isinstance(name, six.string_types) and name.startswith('ppa:'):
owner_name, ppa_name = name[4:].split('/')
ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
keyid = ppa_info['signing_key_fingerprint'][-8:]
else:
raise SaltInvocationError(
'keyid_ppa requires that a PPA be passed'
)
else:
if 'keyid' in kwargs:
keyid = kwargs.get('keyid')
else:
raise SaltInvocationError(
'keyid or keyid_ppa and PPA name must be passed'
)
result = _call_apt(['apt-key', 'del', keyid], scope=False)
if result['retcode'] != 0:
msg = 'Failed to remove keyid {0}'
if result['stderr']:
msg += ': {0}'.format(result['stderr'])
raise CommandExecutionError(msg)
return keyid
def mod_repo(repo, saltenv='base', **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the definition is well formed. For Ubuntu the
``ppa:<project>/repo`` format is acceptable. ``ppa:`` format can only be
used to create a new repository.
The following options are available to modify a repo definition:
architectures
A comma-separated list of supported architectures, e.g. ``amd64`` If
this option is not set, all architectures (configured in the system)
will be used.
comps
A comma separated list of components for the repo, e.g. ``main``
file
A file name to be used
keyserver
Keyserver to get gpg key from
keyid
Key ID or a list of key IDs to load with the ``keyserver`` argument
key_url
URL to a GPG key to add to the APT GPG keyring
key_text
GPG key in string form to add to the APT GPG keyring
.. versionadded:: 2018.3.0
consolidate : False
If ``True``, will attempt to de-duplicate and consolidate sources
comments
Sometimes you want to supply additional information, but not as
enabled configuration. All comments provided here will be joined
into a single string and appended to the repo configuration with a
comment marker (#) before it.
.. versionadded:: 2015.8.9
.. note::
Due to the way keys are stored for APT, there is a known issue where
the key won't be updated unless another change is made at the same
time. Keys should be properly added on initial configuration.
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo 'myrepo definition' uri=http://new/uri
salt '*' pkg.mod_repo 'myrepo definition' comps=main,universe
'''
if 'refresh_db' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'refresh_db\' argument to \'pkg.mod_repo\' has been '
'renamed to \'refresh\'. Support for using \'refresh_db\' will be '
'removed in the Neon release of Salt.'
)
refresh = kwargs['refresh_db']
else:
refresh = kwargs.get('refresh', True)
_check_apt()
# to ensure no one sets some key values that _shouldn't_ be changed on the
# object itself, this is just a white-list of "ok" to set properties
if repo.startswith('ppa:'):
if __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
# secure PPAs cannot be supported as of the time of this code
# implementation via apt-add-repository. The code path for
# secure PPAs should be the same as urllib method
if salt.utils.path.which('apt-add-repository') \
and 'ppa_auth' not in kwargs:
repo_info = get_repo(repo)
if repo_info:
return {repo: repo_info}
else:
env = None
http_proxy_url = _get_http_proxy_url()
if http_proxy_url:
env = {'http_proxy': http_proxy_url,
'https_proxy': http_proxy_url}
if float(__grains__['osrelease']) < 12.04:
cmd = ['apt-add-repository', repo]
else:
cmd = ['apt-add-repository', '-y', repo]
out = _call_apt(cmd, env=env, scope=False, **kwargs)
if out['retcode']:
raise CommandExecutionError(
'Unable to add PPA \'{0}\'. \'{1}\' exited with '
'status {2!s}: \'{3}\' '.format(
repo[4:],
cmd,
out['retcode'],
out['stderr']
)
)
# explicit refresh when a repo is modified.
if refresh:
refresh_db()
return {repo: out}
else:
if not HAS_SOFTWAREPROPERTIES:
_warn_software_properties(repo)
else:
log.info('Falling back to urllib method for private PPA')
# fall back to urllib style
try:
owner_name, ppa_name = repo[4:].split('/', 1)
except ValueError:
raise CommandExecutionError(
'Unable to get PPA info from argument. '
'Expected format "<PPA_OWNER>/<PPA_NAME>" '
'(e.g. saltstack/salt) not found. Received '
'\'{0}\' instead.'.format(repo[4:])
)
dist = __grains__['lsb_distrib_codename']
# ppa has a lot of implicit arguments. Make them explicit.
# These will defer to any user-defined variants
kwargs['dist'] = dist
ppa_auth = ''
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name,
dist)
try:
launchpad_ppa_info = _get_ppa_info_from_launchpad(
owner_name, ppa_name)
if 'ppa_auth' not in kwargs:
kwargs['keyid'] = launchpad_ppa_info[
'signing_key_fingerprint']
else:
if 'keyid' not in kwargs:
error_str = 'Private PPAs require a ' \
'keyid to be specified: {0}/{1}'
raise CommandExecutionError(
error_str.format(owner_name, ppa_name)
)
except HTTPError as exc:
raise CommandExecutionError(
'Launchpad does not know about {0}/{1}: {2}'.format(
owner_name, ppa_name, exc)
)
except IndexError as exc:
raise CommandExecutionError(
'Launchpad knows about {0}/{1} but did not '
'return a fingerprint. Please set keyid '
'manually: {2}'.format(owner_name, ppa_name, exc)
)
if 'keyserver' not in kwargs:
kwargs['keyserver'] = 'keyserver.ubuntu.com'
if 'ppa_auth' in kwargs:
if not launchpad_ppa_info['private']:
raise CommandExecutionError(
'PPA is not private but auth credentials '
'passed: {0}'.format(repo)
)
# assign the new repo format to the "repo" variable
# so we can fall through to the "normal" mechanism
# here.
if 'ppa_auth' in kwargs:
ppa_auth = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(ppa_auth, owner_name,
ppa_name, dist)
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
else:
raise CommandExecutionError(
'cannot parse "ppa:" style repo definitions: {0}'
.format(repo)
)
sources = sourceslist.SourcesList()
if kwargs.get('consolidate', False):
# attempt to de-dup and consolidate all sources
# down to entries in sources.list
# this option makes it easier to keep the sources
# list in a "sane" state.
#
# this should remove duplicates, consolidate comps
# for a given source down to one line
# and eliminate "invalid" and comment lines
#
# the second side effect is removal of files
# that are not the main sources.list file
sources = _consolidate_repo_sources(sources)
repos = [s for s in sources if not s.invalid]
mod_source = None
try:
repo_type, \
repo_architectures, \
repo_uri, \
repo_dist, \
repo_comps = _split_repo_str(repo)
except SyntaxError:
raise SyntaxError(
'Error: repo \'{0}\' not a well formatted definition'.format(repo)
)
full_comp_list = set(repo_comps)
no_proxy = __salt__['config.option']('no_proxy')
if 'keyid' in kwargs:
keyid = kwargs.pop('keyid', None)
keyserver = kwargs.pop('keyserver', None)
if not keyid or not keyserver:
error_str = 'both keyserver and keyid options required.'
raise NameError(error_str)
if not isinstance(keyid, list):
keyid = [keyid]
for key in keyid:
if isinstance(key, int): # yaml can make this an int, we need the hex version
key = hex(key)
cmd = ['apt-key', 'export', key]
output = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
imported = output.startswith('-----BEGIN PGP')
if keyserver:
if not imported:
http_proxy_url = _get_http_proxy_url()
if http_proxy_url and keyserver not in no_proxy:
cmd = ['apt-key', 'adv', '--batch', '--keyserver-options', 'http-proxy={0}'.format(http_proxy_url),
'--keyserver', keyserver, '--logger-fd', '1', '--recv-keys', key]
else:
cmd = ['apt-key', 'adv', '--batch', '--keyserver', keyserver,
'--logger-fd', '1', '--recv-keys', key]
ret = _call_apt(cmd, scope=False, **kwargs)
if ret['retcode'] != 0:
raise CommandExecutionError(
'Error: key retrieval failed: {0}'.format(ret['stdout'])
)
elif 'key_url' in kwargs:
key_url = kwargs['key_url']
fn_ = __salt__['cp.cache_file'](key_url, saltenv)
if not fn_:
raise CommandExecutionError(
'Error: file not found: {0}'.format(key_url)
)
cmd = ['apt-key', 'add', fn_]
out = __salt__['cmd.run_stdout'](cmd, python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key from {0}'.format(key_url)
)
elif 'key_text' in kwargs:
key_text = kwargs['key_text']
cmd = ['apt-key', 'add', '-']
out = __salt__['cmd.run_stdout'](cmd, stdin=key_text,
python_shell=False, **kwargs)
if not out.upper().startswith('OK'):
raise CommandExecutionError(
'Error: failed to add key:\n{0}'.format(key_text)
)
if 'comps' in kwargs:
kwargs['comps'] = kwargs['comps'].split(',')
full_comp_list |= set(kwargs['comps'])
else:
kwargs['comps'] = list(full_comp_list)
if 'architectures' in kwargs:
kwargs['architectures'] = kwargs['architectures'].split(',')
else:
kwargs['architectures'] = repo_architectures
if 'disabled' in kwargs:
kwargs['disabled'] = salt.utils.data.is_true(kwargs['disabled'])
kw_type = kwargs.get('type')
kw_dist = kwargs.get('dist')
for source in repos:
# This series of checks will identify the starting source line
# and the resulting source line. The idea here is to ensure
# we are not returning bogus data because the source line
# has already been modified on a previous run.
repo_matches = source.type == repo_type and source.uri.rstrip('/') == repo_uri.rstrip('/') and source.dist == repo_dist
kw_matches = source.dist == kw_dist and source.type == kw_type
if repo_matches or kw_matches:
for comp in full_comp_list:
if comp in getattr(source, 'comps', []):
mod_source = source
if not source.comps:
mod_source = source
if kwargs['architectures'] != source.architectures:
mod_source = source
if mod_source:
break
if 'comments' in kwargs:
kwargs['comments'] = \
salt.utils.pkg.deb.combine_comments(kwargs['comments'])
if not mod_source:
mod_source = sourceslist.SourceEntry(repo)
if 'comments' in kwargs:
mod_source.comment = kwargs['comments']
sources.list.append(mod_source)
elif 'comments' in kwargs:
mod_source.comment = kwargs['comments']
for key in kwargs:
if key in _MODIFY_OK and hasattr(mod_source, key):
setattr(mod_source, key, kwargs[key])
sources.save()
# on changes, explicitly refresh
if refresh:
refresh_db()
return {
repo: {
'architectures': getattr(mod_source, 'architectures', []),
'comps': mod_source.comps,
'disabled': mod_source.disabled,
'file': mod_source.file,
'type': mod_source.type,
'uri': mod_source.uri,
'line': mod_source.line
}
}
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
return __salt__['lowpkg.file_list'](*packages)
def file_dict(*packages, **kwargs):
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_dict httpd
salt '*' pkg.file_dict httpd postfix
salt '*' pkg.file_dict
'''
return __salt__['lowpkg.file_dict'](*packages)
def expand_repo_def(**kwargs):
'''
Take a repository definition and expand it to the full pkg repository dict
that can be used for comparison. This is a helper function to make
the Debian/Ubuntu apt sources sane for comparison in the pkgrepo states.
This is designed to be called from pkgrepo states and will have little use
being called on the CLI.
'''
if 'repo' not in kwargs:
raise SaltInvocationError('missing \'repo\' argument')
_check_apt()
sanitized = {}
repo = salt.utils.pkg.deb.strip_uri(kwargs['repo'])
if repo.startswith('ppa:') and __grains__['os'] in ('Ubuntu', 'Mint', 'neon'):
dist = __grains__['lsb_distrib_codename']
owner_name, ppa_name = repo[4:].split('/', 1)
if 'ppa_auth' in kwargs:
auth_info = '{0}@'.format(kwargs['ppa_auth'])
repo = LP_PVT_SRC_FORMAT.format(auth_info, owner_name, ppa_name,
dist)
else:
if HAS_SOFTWAREPROPERTIES:
if hasattr(softwareproperties.ppa, 'PPAShortcutHandler'):
repo = softwareproperties.ppa.PPAShortcutHandler(repo).expand(dist)[0]
else:
repo = softwareproperties.ppa.expand_ppa_line(repo, dist)[0]
else:
repo = LP_SRC_FORMAT.format(owner_name, ppa_name, dist)
if 'file' not in kwargs:
filename = '/etc/apt/sources.list.d/{0}-{1}-{2}.list'
kwargs['file'] = filename.format(owner_name, ppa_name, dist)
source_entry = sourceslist.SourceEntry(repo)
for list_args in ('architectures', 'comps'):
if list_args in kwargs:
kwargs[list_args] = kwargs[list_args].split(',')
for kwarg in _MODIFY_OK:
if kwarg in kwargs:
setattr(source_entry, kwarg, kwargs[kwarg])
sanitized['file'] = source_entry.file
sanitized['comps'] = getattr(source_entry, 'comps', [])
sanitized['disabled'] = source_entry.disabled
sanitized['dist'] = source_entry.dist
sanitized['type'] = source_entry.type
sanitized['uri'] = source_entry.uri.rstrip('/')
sanitized['line'] = source_entry.line.strip()
sanitized['architectures'] = getattr(source_entry, 'architectures', [])
return sanitized
def _parse_selections(dpkgselection):
'''
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
'''
ret = {}
if isinstance(dpkgselection, six.string_types):
dpkgselection = dpkgselection.split('\n')
for line in dpkgselection:
if line:
_pkg, _state = line.split()
if _state in ret:
ret[_state].append(_pkg)
else:
ret[_state] = [_pkg]
return ret
def get_selections(pattern=None, state=None):
'''
View package state from the dpkg database.
Returns a dict of dicts containing the state, and package names:
.. code-block:: python
{'<host>':
{'<state>': ['pkg1',
...
]
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.get_selections
salt '*' pkg.get_selections 'python-*'
salt '*' pkg.get_selections state=hold
salt '*' pkg.get_selections 'openssh*' state=hold
'''
ret = {}
cmd = ['dpkg', '--get-selections']
cmd.append(pattern if pattern else '*')
stdout = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret = _parse_selections(stdout)
if state:
return {state: ret.get(state, [])}
return ret
# TODO: allow state=None to be set, and that *args will be set to that state
# TODO: maybe use something similar to pkg_resources.pack_pkgs to allow a list
# passed to selection, with the default state set to whatever is passed by the
# above, but override that if explicitly specified
# TODO: handle path to selection file from local fs as well as from salt file
# server
def set_selections(path=None, selection=None, clear=False, saltenv='base'):
'''
Change package state in the dpkg database.
The state can be any one of, documented in ``dpkg(1)``:
- install
- hold
- deinstall
- purge
This command is commonly used to mark specific packages to be held from
being upgraded, that is, to be kept at a certain version. When a state is
changed to anything but being held, then it is typically followed by
``apt-get -u dselect-upgrade``.
Note: Be careful with the ``clear`` argument, since it will start
with setting all packages to deinstall state.
Returns a dict of dicts containing the package names, and the new and old
versions:
.. code-block:: python
{'<host>':
{'<package>': {'new': '<new-state>',
'old': '<old-state>'}
},
...
}
CLI Example:
.. code-block:: bash
salt '*' pkg.set_selections selection='{"install": ["netcat"]}'
salt '*' pkg.set_selections selection='{"hold": ["openssh-server", "openssh-client"]}'
salt '*' pkg.set_selections salt://path/to/file
salt '*' pkg.set_selections salt://path/to/file clear=True
'''
ret = {}
if not path and not selection:
return ret
if path and selection:
err = ('The \'selection\' and \'path\' arguments to '
'pkg.set_selections are mutually exclusive, and cannot be '
'specified together')
raise SaltInvocationError(err)
if isinstance(selection, six.string_types):
try:
selection = salt.utils.yaml.safe_load(selection)
except (salt.utils.yaml.parser.ParserError, salt.utils.yaml.scanner.ScannerError) as exc:
raise SaltInvocationError(
'Improperly-formatted selection: {0}'.format(exc)
)
if path:
path = __salt__['cp.cache_file'](path, saltenv)
with salt.utils.files.fopen(path, 'r') as ifile:
content = [salt.utils.stringutils.to_unicode(x)
for x in ifile.readlines()]
selection = _parse_selections(content)
if selection:
valid_states = ('install', 'hold', 'deinstall', 'purge')
bad_states = [x for x in selection if x not in valid_states]
if bad_states:
raise SaltInvocationError(
'Invalid state(s): {0}'.format(', '.join(bad_states))
)
if clear:
cmd = ['dpkg', '--clear-selections']
if not __opts__['test']:
result = _call_apt(cmd, scope=False)
if result['retcode'] != 0:
err = ('Running dpkg --clear-selections failed: '
'{0}'.format(result['stderr']))
log.error(err)
raise CommandExecutionError(err)
sel_revmap = {}
for _state, _pkgs in six.iteritems(get_selections()):
sel_revmap.update(dict((_pkg, _state) for _pkg in _pkgs))
for _state, _pkgs in six.iteritems(selection):
for _pkg in _pkgs:
if _state == sel_revmap.get(_pkg):
continue
cmd = ['dpkg', '--set-selections']
cmd_in = '{0} {1}'.format(_pkg, _state)
if not __opts__['test']:
result = _call_apt(cmd, scope=False, stdin=cmd_in)
if result['retcode'] != 0:
log.error(
'failed to set state %s for package %s',
_state, _pkg
)
else:
ret[_pkg] = {'old': sel_revmap.get(_pkg),
'new': _state}
return ret
def _resolve_deps(name, pkgs, **kwargs):
'''
Installs missing dependencies and marks them as auto installed so they
are removed when no more manually installed packages depend on them.
.. versionadded:: 2014.7.0
:depends: - python-apt module
'''
missing_deps = []
for pkg_file in pkgs:
deb = apt.debfile.DebPackage(filename=pkg_file, cache=apt.Cache())
if deb.check():
missing_deps.extend(deb.missing_deps)
if missing_deps:
cmd = ['apt-get', '-q', '-y']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confold']
cmd = cmd + ['-o', 'DPkg::Options::=--force-confdef']
cmd.append('install')
cmd.extend(missing_deps)
ret = __salt__['cmd.retcode'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
if ret != 0:
raise CommandExecutionError(
'Error: unable to resolve dependencies for: {0}'.format(name)
)
else:
try:
cmd = ['apt-mark', 'auto'] + missing_deps
__salt__['cmd.run'](
cmd,
env=kwargs.get('env'),
python_shell=False
)
except MinionError as exc:
raise CommandExecutionError(exc)
return
def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.aptpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
for path in paths:
cmd = ['dpkg', '-S', path]
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
ret[path] = output.split(':')[0]
if 'no path found' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def show(*names, **kwargs):
'''
.. versionadded:: 2019.2.0
Runs an ``apt-cache show`` on the passed package names, and returns the
results in a nested dictionary. The top level of the return data will be
the package name, with each package name mapping to a dictionary of version
numbers to any additional information returned by ``apt-cache show``.
filter
An optional comma-separated list (or quoted Python list) of
case-insensitive keys on which to filter. This allows one to restrict
the information returned for each package to a smaller selection of
pertinent items.
refresh : False
If ``True``, the apt cache will be refreshed first. By default, no
refresh is performed.
CLI Examples:
.. code-block:: bash
salt myminion pkg.show gawk
salt myminion pkg.show 'nginx-*'
salt myminion pkg.show 'nginx-*' filter=description,provides
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
refresh = kwargs.pop('refresh', False)
filter_ = salt.utils.args.split_input(
kwargs.pop('filter', []),
lambda x: six.text_type(x)
if not isinstance(x, six.string_types)
else x.lower()
)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if refresh:
refresh_db()
if not names:
return {}
result = _call_apt(['apt-cache', 'show'] + list(names), scope=False)
def _add(ret, pkginfo):
name = pkginfo.pop('Package', None)
version = pkginfo.pop('Version', None)
if name is not None and version is not None:
ret.setdefault(name, {}).setdefault(version, {}).update(pkginfo)
def _check_filter(key):
key = key.lower()
return True if key in ('package', 'version') or not filter_ \
else key in filter_
ret = {}
pkginfo = {}
for line in salt.utils.itertools.split(result['stdout'], '\n'):
line = line.strip()
if line:
try:
key, val = [x.strip() for x in line.split(':', 1)]
except ValueError:
pass
else:
if _check_filter(key):
pkginfo[key] = val
else:
# We've reached a blank line, which separates packages
_add(ret, pkginfo)
# Clear out the pkginfo dict for the next package
pkginfo = {}
continue
# Make sure to add whatever was in the pkginfo dict when we reached the end
# of the output.
_add(ret, pkginfo)
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s) installed on the system.
.. versionadded:: 2015.8.1
names
The names of the packages for which to return information.
failhard
Whether to throw an exception if none of the packages are installed.
Defaults to True.
.. versionadded:: 2016.11.3
attr
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
version, vendor, release, build_date, build_date_time_t, install_date, install_date_time_t,
build_host, group, source_rpm, arch, epoch, size, license, signature, packager, url, summary, description.
.. versionadded:: Neon
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> failhard=false
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
failhard = kwargs.pop('failhard', True)
kwargs.pop('errors', None) # Only for compatibility with RPM
attr = kwargs.pop('attr', None) # Package attributes to return
all_versions = kwargs.pop('all_versions', False) # This is for backward compatible structure only
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
ret = dict()
for pkg_name, pkg_nfo in __salt__['lowpkg.info'](*names, failhard=failhard, attr=attr).items():
t_nfo = dict()
if pkg_nfo.get('status', 'ii')[1] != 'i':
continue # return only packages that are really installed
# Translate dpkg-specific keys to a common structure
for key, value in pkg_nfo.items():
if key == 'package':
t_nfo['name'] = value
elif key == 'origin':
t_nfo['vendor'] = value
elif key == 'section':
t_nfo['group'] = value
elif key == 'maintainer':
t_nfo['packager'] = value
elif key == 'homepage':
t_nfo['url'] = value
elif key == 'status':
continue # only installed pkgs are returned, no need for status
else:
t_nfo[key] = value
if all_versions:
ret.setdefault(pkg_name, []).append(t_nfo)
else:
ret[pkg_name] = t_nfo
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
_diff_and_merge_host_list
|
python
|
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
|
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L217-L233
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
_get_existing_template_c_list
|
python
|
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
|
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L236-L261
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
_adjust_object_lists
|
python
|
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
|
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L264-L273
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
_manage_component
|
python
|
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
|
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L276-L339
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
is_present
|
python
|
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
|
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L342-L371
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
present
|
python
|
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
|
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L375-L699
|
[
"def _diff_and_merge_host_list(defined, existing):\n '''\n If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent\n some externally assigned hosts to be detached.\n\n :param defined: list of hosts defined in sls\n :param existing: list of hosts taken from live Zabbix\n :return: list to be updated (combinated or empty list)\n '''\n try:\n defined_host_ids = set([host['hostid'] for host in defined])\n existing_host_ids = set([host['hostid'] for host in existing])\n except KeyError:\n raise SaltException('List of hosts in template not defined correctly.')\n\n diff = defined_host_ids - existing_host_ids\n return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []\n",
"def _get_existing_template_c_list(component, parent_id, **kwargs):\n '''\n Make a list of given component type not inherited from other templates because Zabbix API returns only list of all\n and list of inherited component items so we have to do a difference list.\n\n :param component: Template component (application, item, etc...)\n :param parent_id: ID of existing template the component is assigned to\n :return List of non-inherited (own) components\n '''\n c_def = TEMPLATE_COMPONENT_DEF[component]\n q_params = dict(c_def['output'])\n q_params.update({c_def['qselectpid']: parent_id})\n\n existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)\n\n # in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)\n if c_def['inherited'] == 'inherited':\n q_params.update({c_def['inherited']: 'true'})\n existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)\n else:\n existing_clist_inherited = []\n\n if existing_clist_inherited:\n return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]\n\n return existing_clist_all\n",
"def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):\n '''\n Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.\n\n :param component: component name\n :param parent_id: ID of parent entity under which component should be created\n :param defined: list of defined items of named component\n :param existing: list of existing items of named component\n :param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)\n '''\n zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()\n\n dry_run = __opts__['test']\n c_def = TEMPLATE_COMPONENT_DEF[component]\n compare_key = c_def['filter']\n\n defined_set = set([item[compare_key] for item in defined])\n existing_set = set([item[compare_key] for item in existing])\n\n create_set = defined_set - existing_set\n update_set = defined_set & existing_set\n delete_set = existing_set - defined_set\n\n create_list = [item for item in defined if item[compare_key] in create_set]\n for object_params in create_list:\n if parent_id:\n object_params.update({c_def['pid_ref_name']: parent_id})\n\n if 'pid_ref_name2' in c_def:\n object_params.update({c_def['pid_ref_name2']: template_id})\n\n _adjust_object_lists(object_params)\n\n if not dry_run:\n object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)\n if object_create:\n object_ids = object_create[c_def['res_id_name']]\n CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,\n c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})\n else:\n CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,\n 'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})\n\n delete_list = [item for item in existing if item[compare_key] in delete_set]\n for object_del in delete_list:\n object_id_name = zabbix_id_mapper[c_def['qtype']]\n CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})\n if not dry_run:\n __salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)\n\n for object_name in update_set:\n ditem = next((item for item in defined if item[compare_key] == object_name), None)\n eitem = next((item for item in existing if item[compare_key] == object_name), None)\n diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)\n\n if diff_params['new']:\n diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]\n diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]\n _adjust_object_lists(diff_params['new'])\n _adjust_object_lists(diff_params['old'])\n CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})\n\n if not dry_run:\n __salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
saltstack/salt
|
salt/states/zabbix_template.py
|
absent
|
python
|
def absent(name, **kwargs):
'''
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
'''
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
if dry_run:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" would be deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" exists.'.format(name),
'new': 'Zabbix Template "{0}" would be deleted.'.format(name)}}
else:
tmpl_delete = __salt__['zabbix.run_query']('template.delete', [object_id], **kwargs)
if tmpl_delete:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" deleted.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" existed.'.format(name),
'new': 'Zabbix Template "{0}" deleted.'.format(name)}}
return ret
|
Makes the Zabbix Template to be absent (either does not exist or delete it).
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
zabbix-template-absent:
zabbix_template.absent:
- name: Ceph OSD
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_template.py#L702-L742
| null |
# -*- coding: utf-8 -*-
'''
.. versionadded:: 2017.7
Management of Zabbix Template object over Zabbix API.
:codeauthor: Jakub Sliva <jakub.sliva@ultimum.io>
'''
from __future__ import absolute_import
from __future__ import unicode_literals
import logging
import json
try:
from salt.ext import six
from salt.exceptions import SaltException
IMPORTS_OK = True
except ImportError:
IMPORTS_OK = False
log = logging.getLogger(__name__)
TEMPLATE_RELATIONS = ['groups', 'hosts', 'macros']
TEMPLATE_COMPONENT_ORDER = ('applications',
'items',
'gitems',
'graphs',
'screens',
'httpTests',
'triggers',
'discoveries')
DISCOVERYRULE_COMPONENT_ORDER = ('itemprototypes', 'triggerprototypes', 'graphprototypes', 'hostprototypes')
TEMPLATE_COMPONENT_DEF = {
# 'component': {'qtype': 'component type to query',
# 'qidname': 'component id name',
# 'qselectpid': 'particular component selection attribute name (parent id name)',
# 'ptype': 'parent component type',
# 'pid': 'parent component id',
# 'pid_ref_name': 'component's creation reference name for parent id',
# 'res_id_name': 'jsonrpc modification call result key name of list of affected IDs'},
# 'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
# 'inherited': 'attribute name for inheritance toggling',
# 'filter': 'child component unique identification attribute name',
'applications': {'qtype': 'application',
'qidname': 'applicationid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'applicationids',
'output': {'output': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': True,
'filter': 'name',
'ro_attrs': ['applicationid', 'flags', 'templateids']},
'items': {'qtype': 'item',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectApplications': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['itemid', 'error', 'flags', 'lastclock', 'lastns',
'lastvalue', 'prevvalue', 'state', 'templateid']},
'triggers': {'qtype': 'trigger',
'qidname': 'triggerid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectDependencies': 'expand',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['error', 'flags', 'lastchange', 'state', 'templateid', 'value']},
'graphs': {'qtype': 'graph',
'qidname': 'graphid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'flags', 'templateid']},
'gitems': {'qtype': 'graphitem',
'qidname': 'itemid',
'qselectpid': 'graphids',
'ptype': 'graph',
'pid': 'graphid',
'pid_ref_name': None,
'res_id_name': None,
'output': {'output': 'extend'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['gitemid']},
# "Template screen"
'screens': {'qtype': 'templatescreen',
'qidname': 'screenid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'templateid',
'res_id_name': 'screenids',
'output': {'output': 'extend', 'selectUsers': 'extend', 'selectUserGroups': 'extend',
'selectScreenItems': 'extend', 'noInheritance': 'true'},
'inherited': 'noInheritance',
'adjust': False,
'filter': 'name',
'ro_attrs': ['screenid']},
# "LLD rule"
'discoveries': {'qtype': 'discoveryrule',
'qidname': 'itemid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectFilter': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'key_',
'ro_attrs': ['itemid', 'error', 'state', 'templateid']},
# "Web scenario"
'httpTests': {'qtype': 'httptest',
'qidname': 'httptestid',
'qselectpid': 'templateids',
'ptype': 'template',
'pid': 'templateid',
'pid_ref_name': 'hostid',
'res_id_name': 'httptestids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['httptestid', 'nextcheck', 'templateid']},
# discoveries => discoveryrule
'itemprototypes': {'qtype': 'itemprototype',
'qidname': 'itemid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
# exception only in case of itemprototype - needs both parent ruleid and hostid
'pid_ref_name2': 'hostid',
'res_id_name': 'itemids',
'output': {'output': 'extend', 'selectSteps': 'extend', 'selectApplications': 'extend',
'templated': 'true'},
'adjust': False,
'inherited': 'inherited',
'filter': 'name',
'ro_attrs': ['itemid', 'templateid']},
'triggerprototypes': {'qtype': 'triggerprototype',
'qidname': 'triggerid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'triggerids',
'output': {'output': 'extend', 'selectTags': 'extend', 'selectDependencies': 'extend',
'templated': 'true', 'expandExpression': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'description',
'ro_attrs': ['triggerid', 'templateid']},
'graphprototypes': {'qtype': 'graphprototype',
'qidname': 'graphid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': None,
'res_id_name': 'graphids',
'output': {'output': 'extend', 'selectGraphItems': 'extend', 'templated': 'true'},
'inherited': 'inherited',
'adjust': False,
'filter': 'name',
'ro_attrs': ['graphid', 'templateid']},
'hostprototypes': {'qtype': 'hostprototype',
'qidname': 'hostid',
'qselectpid': 'discoveryids',
'ptype': 'discoveryrule',
'pid': 'itemid',
'pid_ref_name': 'ruleid',
'res_id_name': 'hostids',
'output': {'output': 'extend', 'selectGroupLinks': 'expand', 'selectGroupPrototypes': 'expand',
'selectTemplates': 'expand'},
'inherited': 'inherited',
'adjust': False,
'filter': 'host',
'ro_attrs': ['hostid', 'templateid']}
}
# CHANGE_STACK = [{'component': 'items', 'action': 'create', 'params': dict|list}]
CHANGE_STACK = []
def __virtual__():
'''
Only make these states available if Zabbix module and run_query function is available
and all 3rd party modules imported.
'''
if 'zabbix.run_query' in __salt__ and IMPORTS_OK:
return True
return False, 'Import zabbix or other needed modules failed.'
def _diff_and_merge_host_list(defined, existing):
'''
If Zabbix template is to be updated then list of assigned hosts must be provided in all or nothing manner to prevent
some externally assigned hosts to be detached.
:param defined: list of hosts defined in sls
:param existing: list of hosts taken from live Zabbix
:return: list to be updated (combinated or empty list)
'''
try:
defined_host_ids = set([host['hostid'] for host in defined])
existing_host_ids = set([host['hostid'] for host in existing])
except KeyError:
raise SaltException('List of hosts in template not defined correctly.')
diff = defined_host_ids - existing_host_ids
return [{'hostid': six.text_type(hostid)} for hostid in diff | existing_host_ids] if diff else []
def _get_existing_template_c_list(component, parent_id, **kwargs):
'''
Make a list of given component type not inherited from other templates because Zabbix API returns only list of all
and list of inherited component items so we have to do a difference list.
:param component: Template component (application, item, etc...)
:param parent_id: ID of existing template the component is assigned to
:return List of non-inherited (own) components
'''
c_def = TEMPLATE_COMPONENT_DEF[component]
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: parent_id})
existing_clist_all = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
# in some cases (e.g. templatescreens) the logic is reversed (even name of the flag is different!)
if c_def['inherited'] == 'inherited':
q_params.update({c_def['inherited']: 'true'})
existing_clist_inherited = __salt__['zabbix.run_query'](c_def['qtype'] + '.get', q_params, **kwargs)
else:
existing_clist_inherited = []
if existing_clist_inherited:
return [c_all for c_all in existing_clist_all if c_all not in existing_clist_inherited]
return existing_clist_all
def _adjust_object_lists(obj):
'''
For creation or update of object that have attribute which contains a list Zabbix awaits plain list of IDs while
querying Zabbix for same object returns list of dicts
:param obj: Zabbix object parameters
'''
for subcomp in TEMPLATE_COMPONENT_DEF:
if subcomp in obj and TEMPLATE_COMPONENT_DEF[subcomp]['adjust']:
obj[subcomp] = [item[TEMPLATE_COMPONENT_DEF[subcomp]['qidname']] for item in obj[subcomp]]
def _manage_component(component, parent_id, defined, existing, template_id=None, **kwargs):
'''
Takes particular component list, compares it with existing, call appropriate API methods - create, update, delete.
:param component: component name
:param parent_id: ID of parent entity under which component should be created
:param defined: list of defined items of named component
:param existing: list of existing items of named component
:param template_id: In case that component need also template ID for creation (although parent_id is given?!?!?)
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
c_def = TEMPLATE_COMPONENT_DEF[component]
compare_key = c_def['filter']
defined_set = set([item[compare_key] for item in defined])
existing_set = set([item[compare_key] for item in existing])
create_set = defined_set - existing_set
update_set = defined_set & existing_set
delete_set = existing_set - defined_set
create_list = [item for item in defined if item[compare_key] in create_set]
for object_params in create_list:
if parent_id:
object_params.update({c_def['pid_ref_name']: parent_id})
if 'pid_ref_name2' in c_def:
object_params.update({c_def['pid_ref_name2']: template_id})
_adjust_object_lists(object_params)
if not dry_run:
object_create = __salt__['zabbix.run_query'](c_def['qtype'] + '.create', object_params, **kwargs)
if object_create:
object_ids = object_create[c_def['res_id_name']]
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
c_def['filter']: object_params[c_def['filter']], 'object_id': object_ids})
else:
CHANGE_STACK.append({'component': component, 'action': 'create', 'params': object_params,
'object_id': 'CREATED '+TEMPLATE_COMPONENT_DEF[component]['qtype']+' ID'})
delete_list = [item for item in existing if item[compare_key] in delete_set]
for object_del in delete_list:
object_id_name = zabbix_id_mapper[c_def['qtype']]
CHANGE_STACK.append({'component': component, 'action': 'delete', 'params': [object_del[object_id_name]]})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.delete', [object_del[object_id_name]], **kwargs)
for object_name in update_set:
ditem = next((item for item in defined if item[compare_key] == object_name), None)
eitem = next((item for item in existing if item[compare_key] == object_name), None)
diff_params = __salt__['zabbix.compare_params'](ditem, eitem, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
diff_params['old'][zabbix_id_mapper[c_def['qtype']]] = eitem[zabbix_id_mapper[c_def['qtype']]]
_adjust_object_lists(diff_params['new'])
_adjust_object_lists(diff_params['old'])
CHANGE_STACK.append({'component': component, 'action': 'update', 'params': diff_params['new']})
if not dry_run:
__salt__['zabbix.run_query'](c_def['qtype'] + '.update', diff_params['new'], **kwargs)
def is_present(name, **kwargs):
'''
Check if Zabbix Template already exists.
:param name: Zabbix Template name
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
does_zabbix-template-exist:
zabbix_template.is_present:
- name: Template OS Linux
'''
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
try:
object_id = __salt__['zabbix.get_object_id_by_params']('template', {'filter': {'name': name}}, **kwargs)
except SaltException:
object_id = False
if not object_id:
ret['result'] = False
ret['comment'] = 'Zabbix Template "{0}" does not exist.'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" exists.'.format(name)
return ret
# pylint: disable=too-many-statements,too-many-locals
def present(name, params, static_host_list=True, **kwargs):
'''
Creates Zabbix Template object or if differs update it according defined parameters. See Zabbix API documentation.
Zabbix API version: >3.0
:param name: Zabbix Template name
:param params: Additional parameters according to Zabbix API documentation
:param static_host_list: If hosts assigned to the template are controlled
only by this state or can be also assigned externally
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. note::
If there is a need to get a value from current zabbix online (e.g. ids of host groups you want the template
to be associated with), put a dictionary with two keys "query_object" and "query_name" instead of the value.
In this example we want to create template named "Testing Template", assign it to hostgroup Templates,
link it to two ceph nodes and create a macro.
.. note::
IMPORTANT NOTE:
Objects (except for template name) are identified by name (or by other key in some exceptional cases)
so changing name of object means deleting old one and creating new one with new ID !!!
.. note::
NOT SUPPORTED FEATURES:
- linked templates
- trigger dependencies
- groups and group prototypes for host prototypes
SLS Example:
.. code-block:: yaml
zabbix-template-present:
zabbix_template.present:
- name: Testing Template
# Do not touch existing assigned hosts
# True will detach all other hosts than defined here
- static_host_list: False
- params:
description: Template for Ceph nodes
groups:
# groups must already exist
# template must be at least in one hostgroup
- groupid:
query_object: hostgroup
query_name: Templates
macros:
- macro: "{$CEPH_CLUSTER_NAME}"
value: ceph
hosts:
# hosts must already exist
- hostid:
query_object: host
query_name: ceph-osd-01
- hostid:
query_object: host
query_name: ceph-osd-02
# templates:
# Linked templates - not supported by state module but can be linked manually (will not be touched)
applications:
- name: Ceph OSD
items:
- name: Ceph OSD avg fill item
key_: ceph.osd_avg_fill
type: 2
value_type: 0
delay: 60
units: '%'
description: 'Average fill of OSD'
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggers:
- description: "Ceph OSD filled more that 90%"
expression: "{{'{'}}Testing Template:ceph.osd_avg_fill.last(){{'}'}}>90"
priority: 4
discoveries:
- name: Mounted filesystem discovery
key_: vfs.fs.discovery
type: 0
delay: 60
itemprototypes:
- name: Free disk space on {{'{#'}}FSNAME}
key_: vfs.fs.size[{{'{#'}}FSNAME},free]
type: 0
value_type: 3
delay: 60
applications:
- applicationid:
query_object: application
query_name: Ceph OSD
triggerprototypes:
- description: "Free disk space is less than 20% on volume {{'{#'}}FSNAME{{'}'}}"
expression: "{{'{'}}Testing Template:vfs.fs.size[{{'{#'}}FSNAME},free].last(){{'}'}}<20"
graphs:
- name: Ceph OSD avg fill graph
width: 900
height: 200
graphtype: 0
gitems:
- color: F63100
itemid:
query_object: item
query_name: Ceph OSD avg fill item
screens:
- name: Ceph
hsize: 1
vsize: 1
screenitems:
- x: 0
y: 0
resourcetype: 0
resourceid:
query_object: graph
query_name: Ceph OSD avg fill graph
'''
zabbix_id_mapper = __salt__['zabbix.get_zabbix_id_mapper']()
dry_run = __opts__['test']
ret = {'name': name, 'result': False, 'comment': '', 'changes': {}}
params['host'] = name
del CHANGE_STACK[:]
# Divide template yaml definition into parts
# - template definition itself
# - simple template components
# - components that have other sub-components
# (e.g. discoveries - where parent ID is needed in advance for sub-component manipulation)
template_definition = {}
template_components = {}
discovery_components = []
for attr in params:
if attr in TEMPLATE_COMPONENT_ORDER and six.text_type(attr) != 'discoveries':
template_components[attr] = params[attr]
elif six.text_type(attr) == 'discoveries':
d_rules = []
for d_rule in params[attr]:
d_rule_components = {'query_pid': {'component': attr,
'filter_val': d_rule[TEMPLATE_COMPONENT_DEF[attr]['filter']]}}
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
if proto_name in d_rule:
d_rule_components[proto_name] = d_rule[proto_name]
del d_rule[proto_name]
discovery_components.append(d_rule_components)
d_rules.append(d_rule)
template_components[attr] = d_rules
else:
template_definition[attr] = params[attr]
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_COMPONENT_ORDER:
if attr not in template_components:
template_components[attr] = []
# if a component is not defined, it means to remove existing items during update (empty list)
for attr in TEMPLATE_RELATIONS:
template_definition[attr] = params[attr] if attr in params and params[attr] else []
defined_obj = __salt__['zabbix.substitute_params'](template_definition, **kwargs)
log.info('SUBSTITUTED template_definition: %s', six.text_type(json.dumps(defined_obj, indent=4)))
tmpl_get = __salt__['zabbix.run_query']('template.get',
{'output': 'extend', 'selectGroups': 'groupid', 'selectHosts': 'hostid',
'selectTemplates': 'templateid', 'selectMacros': 'extend',
'filter': {'host': name}},
**kwargs)
log.info('TEMPLATE get result: %s', six.text_type(json.dumps(tmpl_get, indent=4)))
existing_obj = __salt__['zabbix.substitute_params'](tmpl_get[0], **kwargs) \
if tmpl_get and len(tmpl_get) == 1 else False
if existing_obj:
template_id = existing_obj[zabbix_id_mapper['template']]
if not static_host_list:
# Prepare objects for comparison
defined_wo_hosts = defined_obj
if 'hosts' in defined_obj:
defined_hosts = defined_obj['hosts']
del defined_wo_hosts['hosts']
else:
defined_hosts = []
existing_wo_hosts = existing_obj
if 'hosts' in existing_obj:
existing_hosts = existing_obj['hosts']
del existing_wo_hosts['hosts']
else:
existing_hosts = []
# Compare host list separately from the rest of the object comparison since the merged list is needed for
# update
hosts_list = _diff_and_merge_host_list(defined_hosts, existing_hosts)
# Compare objects without hosts
diff_params = __salt__['zabbix.compare_params'](defined_wo_hosts, existing_wo_hosts, True)
# Merge comparison results together
if ('new' in diff_params and 'hosts' in diff_params['new']) or hosts_list:
diff_params['new']['hosts'] = hosts_list
else:
diff_params = __salt__['zabbix.compare_params'](defined_obj, existing_obj, True)
if diff_params['new']:
diff_params['new'][zabbix_id_mapper['template']] = template_id
diff_params['old'][zabbix_id_mapper['template']] = template_id
log.info('TEMPLATE: update params: %s', six.text_type(json.dumps(diff_params, indent=4)))
CHANGE_STACK.append({'component': 'template', 'action': 'update', 'params': diff_params['new']})
if not dry_run:
tmpl_update = __salt__['zabbix.run_query']('template.update', diff_params['new'], **kwargs)
log.info('TEMPLATE update result: %s', six.text_type(tmpl_update))
else:
CHANGE_STACK.append({'component': 'template', 'action': 'create', 'params': defined_obj})
if not dry_run:
tmpl_create = __salt__['zabbix.run_query']('template.create', defined_obj, **kwargs)
log.info('TEMPLATE create result: %s', tmpl_create)
if tmpl_create:
template_id = tmpl_create['templateids'][0]
log.info('\n\ntemplate_components: %s', json.dumps(template_components, indent=4))
log.info('\n\ndiscovery_components: %s', json.dumps(discovery_components, indent=4))
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if existing_obj or not dry_run:
for component in TEMPLATE_COMPONENT_ORDER:
log.info('\n\n\n\n\nCOMPONENT: %s\n\n', six.text_type(json.dumps(component)))
# 1) query for components which belongs to the template
existing_c_list = _get_existing_template_c_list(component, template_id, **kwargs)
existing_c_list_subs = __salt__['zabbix.substitute_params'](existing_c_list, **kwargs) \
if existing_c_list else []
if component in template_components:
defined_c_list_subs = __salt__['zabbix.substitute_params'](
template_components[component],
extend_params={TEMPLATE_COMPONENT_DEF[component]['qselectpid']: template_id},
filter_key=TEMPLATE_COMPONENT_DEF[component]['filter'],
**kwargs)
else:
defined_c_list_subs = []
# 2) take lists of particular component and compare -> do create, update and delete actions
_manage_component(component, template_id, defined_c_list_subs, existing_c_list_subs, **kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
for d_rule_component in discovery_components:
# query for parent id -> "query_pid": {"filter_val": "vfs.fs.discovery", "component": "discoveries"}
q_def = d_rule_component['query_pid']
c_def = TEMPLATE_COMPONENT_DEF[q_def['component']]
q_object = c_def['qtype']
q_params = dict(c_def['output'])
q_params.update({c_def['qselectpid']: template_id})
q_params.update({'filter': {c_def['filter']: q_def['filter_val']}})
parent_id = __salt__['zabbix.get_object_id_by_params'](q_object, q_params, **kwargs)
for proto_name in DISCOVERYRULE_COMPONENT_ORDER:
log.info('\n\n\n\n\nPROTOTYPE_NAME: %s\n\n', six.text_type(json.dumps(proto_name)))
existing_p_list = _get_existing_template_c_list(proto_name, parent_id, **kwargs)
existing_p_list_subs = __salt__['zabbix.substitute_params'](existing_p_list, **kwargs)\
if existing_p_list else []
if proto_name in d_rule_component:
defined_p_list_subs = __salt__['zabbix.substitute_params'](
d_rule_component[proto_name],
extend_params={c_def['qselectpid']: template_id},
**kwargs)
else:
defined_p_list_subs = []
_manage_component(proto_name,
parent_id,
defined_p_list_subs,
existing_p_list_subs,
template_id=template_id,
**kwargs)
log.info('\n\nCurrent CHANGE_STACK: %s', six.text_type(json.dumps(CHANGE_STACK, indent=4)))
if not CHANGE_STACK:
ret['result'] = True
ret['comment'] = 'Zabbix Template "{0}" already exists and corresponds to a definition.'.format(name)
else:
tmpl_action = next((item for item in CHANGE_STACK
if item['component'] == 'template' and item['action'] == 'create'), None)
if tmpl_action:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" does not exist.'.format(name),
'new': 'Zabbix Template "{0}" would be created '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" created.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" did not exist.'.format(name),
'new': 'Zabbix Template "{0}" created according definition.'.format(name)}}
else:
ret['result'] = True
if dry_run:
ret['comment'] = 'Zabbix Template "{0}" would be updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differs.'.format(name),
'new': 'Zabbix Template "{0}" would be updated '
'according definition.'.format(name)}}
else:
ret['comment'] = 'Zabbix Template "{0}" updated.'.format(name)
ret['changes'] = {name: {'old': 'Zabbix Template "{0}" differed.'.format(name),
'new': 'Zabbix Template "{0}" updated according definition.'.format(name)}}
return ret
|
saltstack/salt
|
salt/modules/solaris_group.py
|
chgid
|
python
|
def chgid(name, gid):
'''
Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376
'''
pre_gid = __salt__['file.group_to_gid'](name)
if gid == pre_gid:
return True
cmd = 'groupmod -g {0} {1}'.format(gid, name)
__salt__['cmd.run'](cmd, python_shell=False)
post_gid = __salt__['file.group_to_gid'](name)
if post_gid != pre_gid:
return post_gid == gid
return False
|
Change the gid for a named group
CLI Example:
.. code-block:: bash
salt '*' group.chgid foo 4376
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_group.py#L125-L143
| null |
# -*- coding: utf-8 -*-
'''
Manage groups on Solaris
.. important::
If you feel that Salt should be using this module to manage groups on a
minion, and it is using a different module (or gives an error similar to
*'group.info' is not available*), see :ref:`here
<module-provider-override>`.
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import logging
# Import salt libs
import salt.utils.data
log = logging.getLogger(__name__)
try:
import grp
except ImportError:
pass
# Define the module's virtual name
__virtualname__ = 'group'
def __virtual__():
'''
Set the group module if the kernel is SunOS
'''
if __grains__['kernel'] == 'SunOS':
return __virtualname__
return (False, 'The solaris_group execution module failed to load: '
'only available on Solaris systems.')
def add(name, gid=None, **kwargs):
'''
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
'''
if salt.utils.data.is_true(kwargs.pop('system', False)):
log.warning('solaris_group module does not support the \'system\' '
'argument')
if kwargs:
log.warning('Invalid kwargs passed to group.add')
cmd = 'groupadd '
if gid:
cmd += '-g {0} '.format(gid)
cmd += name
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
return not ret['retcode']
def delete(name):
'''
Remove the named group
CLI Example:
.. code-block:: bash
salt '*' group.delete foo
'''
ret = __salt__['cmd.run_all']('groupdel {0}'.format(name), python_shell=False)
return not ret['retcode']
def info(name):
'''
Return information about a group
CLI Example:
.. code-block:: bash
salt '*' group.info foo
'''
try:
grinfo = grp.getgrnam(name)
except KeyError:
return {}
else:
return {'name': grinfo.gr_name,
'passwd': grinfo.gr_passwd,
'gid': grinfo.gr_gid,
'members': grinfo.gr_mem}
def getent(refresh=False):
'''
Return info on all groups
CLI Example:
.. code-block:: bash
salt '*' group.getent
'''
if 'group.getent' in __context__ and not refresh:
return __context__['group.getent']
ret = []
for grinfo in grp.getgrall():
ret.append(info(grinfo.gr_name))
__context__['group.getent'] = ret
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
gen_key
|
python
|
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
|
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L87-L167
|
[
"def _base_url():\n '''\n Return the base_url\n '''\n return __opts__.get('venafi', {}).get(\n 'base_url', 'https://api.venafi.cloud/v1'\n )\n",
"def _api_key():\n '''\n Return the API key\n '''\n return __opts__.get('venafi', {}).get('api_key', '')\n",
"def store(self, bank, key, data):\n '''\n Store data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :param data:\n The data which will be stored in the cache. This data should be\n in a format which can be serialized by msgpack/json/yaml/etc.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.store'.format(self.driver)\n return self.modules[fun](bank, key, data, **self._kwargs)\n",
"def fetch(self, bank, key):\n '''\n Fetch data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :return:\n Return a python object fetched from the cache or an empty dict if\n the given path or key not found.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.fetch'.format(self.driver)\n return self.modules[fun](bank, key, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
gen_csr
|
python
|
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
|
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L170-L259
|
[
"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 to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def gen_key(minion_id, dns_name=None, zone='default', password=None):\n '''\n Generate and return an private_key. If a ``dns_name`` is passed in, the\n private_key will be cached under that name. The type of key and the\n parameters used to generate the key are based on the default certificate\n use policy associated with the specified zone.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]\n '''\n # Get the default certificate use policy associated with the zone\n # so we can generate keys that conform with policy\n\n # The /v1/zones/tag/{name} API call is a shortcut to get the zoneID\n # directly from the name\n\n qdata = __utils__['http.query'](\n '{0}/zones/tag/{1}'.format(_base_url(), zone),\n method='GET',\n decode=True,\n decode_type='json',\n header_dict={\n 'tppl-api-key': _api_key(),\n 'Content-Type': 'application/json',\n },\n )\n\n zone_id = qdata['dict']['id']\n\n # the /v1/certificatepolicies?zoneId API call returns the default\n # certificate use and certificate identity policies\n\n qdata = __utils__['http.query'](\n '{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),\n method='GET',\n decode=True,\n decode_type='json',\n header_dict={\n 'tppl-api-key': _api_key(),\n 'Content-Type': 'application/json',\n },\n )\n\n policies = qdata['dict']['certificatePolicies']\n\n # Extract the key length and key type from the certificate use policy\n # and generate the private key accordingly\n\n for policy in policies:\n if policy['certificatePolicyType'] == \"CERTIFICATE_USE\":\n keyTypes = policy['keyTypes']\n # in case multiple keytypes and key lengths are supported\n # always use the first key type and key length\n keygen_type = keyTypes[0]['keyType']\n key_len = keyTypes[0]['keyLengths'][0]\n\n if int(key_len) < 2048:\n key_len = 2048\n\n if keygen_type == \"RSA\":\n if HAS_M2:\n gen = RSA.gen_key(key_len, 65537)\n private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))\n else:\n gen = RSA.generate(bits=key_len)\n private_key = gen.exportKey('PEM', password)\n if dns_name is not None:\n bank = 'venafi/domains'\n cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)\n try:\n data = cache.fetch(bank, dns_name)\n data['private_key'] = private_key\n data['minion_id'] = minion_id\n except TypeError:\n data = {'private_key': private_key,\n 'minion_id': minion_id}\n cache.store(bank, dns_name, data)\n return private_key\n",
"def store(self, bank, key, data):\n '''\n Store data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :param data:\n The data which will be stored in the cache. This data should be\n in a format which can be serialized by msgpack/json/yaml/etc.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.store'.format(self.driver)\n return self.modules[fun](bank, key, data, **self._kwargs)\n",
"def fetch(self, bank, key):\n '''\n Fetch data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :return:\n Return a python object fetched from the cache or an empty dict if\n the given path or key not found.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.fetch'.format(self.driver)\n return self.modules[fun](bank, key, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
request
|
python
|
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
|
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L262-L361
|
[
"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 gen_key(minion_id, dns_name=None, zone='default', password=None):\n '''\n Generate and return an private_key. If a ``dns_name`` is passed in, the\n private_key will be cached under that name. The type of key and the\n parameters used to generate the key are based on the default certificate\n use policy associated with the specified zone.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]\n '''\n # Get the default certificate use policy associated with the zone\n # so we can generate keys that conform with policy\n\n # The /v1/zones/tag/{name} API call is a shortcut to get the zoneID\n # directly from the name\n\n qdata = __utils__['http.query'](\n '{0}/zones/tag/{1}'.format(_base_url(), zone),\n method='GET',\n decode=True,\n decode_type='json',\n header_dict={\n 'tppl-api-key': _api_key(),\n 'Content-Type': 'application/json',\n },\n )\n\n zone_id = qdata['dict']['id']\n\n # the /v1/certificatepolicies?zoneId API call returns the default\n # certificate use and certificate identity policies\n\n qdata = __utils__['http.query'](\n '{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),\n method='GET',\n decode=True,\n decode_type='json',\n header_dict={\n 'tppl-api-key': _api_key(),\n 'Content-Type': 'application/json',\n },\n )\n\n policies = qdata['dict']['certificatePolicies']\n\n # Extract the key length and key type from the certificate use policy\n # and generate the private key accordingly\n\n for policy in policies:\n if policy['certificatePolicyType'] == \"CERTIFICATE_USE\":\n keyTypes = policy['keyTypes']\n # in case multiple keytypes and key lengths are supported\n # always use the first key type and key length\n keygen_type = keyTypes[0]['keyType']\n key_len = keyTypes[0]['keyLengths'][0]\n\n if int(key_len) < 2048:\n key_len = 2048\n\n if keygen_type == \"RSA\":\n if HAS_M2:\n gen = RSA.gen_key(key_len, 65537)\n private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))\n else:\n gen = RSA.generate(bits=key_len)\n private_key = gen.exportKey('PEM', password)\n if dns_name is not None:\n bank = 'venafi/domains'\n cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)\n try:\n data = cache.fetch(bank, dns_name)\n data['private_key'] = private_key\n data['minion_id'] = minion_id\n except TypeError:\n data = {'private_key': private_key,\n 'minion_id': minion_id}\n cache.store(bank, dns_name, data)\n return private_key\n",
"def _base_url():\n '''\n Return the base_url\n '''\n return __opts__.get('venafi', {}).get(\n 'base_url', 'https://api.venafi.cloud/v1'\n )\n",
"def _api_key():\n '''\n Return the API key\n '''\n return __opts__.get('venafi', {}).get('api_key', '')\n",
"def gen_csr(\n minion_id,\n dns_name,\n zone='default',\n country=None,\n state=None,\n loc=None,\n org=None,\n org_unit=None,\n password=None,\n ):\n '''\n Generate a csr using the host's private_key.\n Analogous to:\n\n .. code-block:: bash\n\n VCert gencsr -cn [CN Value] -o \"Beta Organization\" -ou \"Beta Group\" \\\n -l \"Palo Alto\" -st \"California\" -c US\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run venafi.gen_csr <minion_id> <dns_name>\n '''\n tmpdir = tempfile.mkdtemp()\n os.chmod(tmpdir, 0o700)\n\n bank = 'venafi/domains'\n cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)\n data = cache.fetch(bank, dns_name)\n if data is None:\n data = {}\n if 'private_key' not in data:\n data['private_key'] = gen_key(minion_id, dns_name, zone, password)\n\n tmppriv = '{0}/priv'.format(tmpdir)\n tmpcsr = '{0}/csr'.format(tmpdir)\n with salt.utils.files.fopen(tmppriv, 'w') as if_:\n if_.write(salt.utils.stringutils.to_str(data['private_key']))\n\n if country is None:\n country = __opts__.get('venafi', {}).get('country')\n\n if state is None:\n state = __opts__.get('venafi', {}).get('state')\n\n if loc is None:\n loc = __opts__.get('venafi', {}).get('loc')\n\n if org is None:\n org = __opts__.get('venafi', {}).get('org')\n\n if org_unit is None:\n org_unit = __opts__.get('venafi', {}).get('org_unit')\n\n subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(\n country,\n state,\n loc,\n org,\n org_unit,\n dns_name,\n )\n\n cmd = \"openssl req -new -sha256 -key {0} -out {1} -subj '{2}'\".format(\n tmppriv,\n tmpcsr,\n subject\n )\n if password is not None:\n cmd += ' -passin pass:{0}'.format(password)\n output = __salt__['salt.cmd']('cmd.run', cmd)\n\n if 'problems making Certificate Request' in output:\n raise CommandExecutionError(\n 'There was a problem generating the CSR. Please ensure that you '\n 'have the following variables set either on the command line, or '\n 'in the venafi section of your master configuration file: '\n 'country, state, loc, org, org_unit'\n )\n\n with salt.utils.files.fopen(tmpcsr, 'r') as of_:\n csr = salt.utils.stringutils.to_unicode(of_.read())\n\n data['minion_id'] = minion_id\n data['csr'] = csr\n cache.store(bank, dns_name, data)\n return csr\n",
"def _id_map(minion_id, dns_name):\n '''\n Maintain a relationship between a minion and a dns name\n '''\n bank = 'venafi/minions'\n cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)\n dns_names = cache.fetch(bank, minion_id)\n if not isinstance(dns_names, list):\n dns_names = []\n if dns_name not in dns_names:\n dns_names.append(dns_name)\n cache.store(bank, minion_id, dns_names)\n",
"def get_zone_id(zone_name):\n '''\n Get the zone ID for the given zone name\n\n CLI Example:\n\n .. code-block:: bash\n\n salt-run venafi.get_zone_id default\n '''\n data = __utils__['http.query'](\n '{0}/zones/tag/{1}'.format(_base_url(), zone_name),\n status=True,\n decode=True,\n decode_type='json',\n header_dict={\n 'tppl-api-key': _api_key(),\n },\n )\n\n status = data['status']\n if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):\n raise CommandExecutionError(\n 'There was an API error: {0}'.format(data['error'])\n )\n return data['dict']['id']\n",
"def store(self, bank, key, data):\n '''\n Store data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :param data:\n The data which will be stored in the cache. This data should be\n in a format which can be serialized by msgpack/json/yaml/etc.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.store'.format(self.driver)\n return self.modules[fun](bank, key, data, **self._kwargs)\n",
"def fetch(self, bank, key):\n '''\n Fetch data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :return:\n Return a python object fetched from the cache or an empty dict if\n the given path or key not found.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.fetch'.format(self.driver)\n return self.modules[fun](bank, key, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
register
|
python
|
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
|
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L382-L411
|
[
"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 _base_url():\n '''\n Return the base_url\n '''\n return __opts__.get('venafi', {}).get(\n 'base_url', 'https://api.venafi.cloud/v1'\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
show_company
|
python
|
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
|
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L414-L438
|
[
"def _base_url():\n '''\n Return the base_url\n '''\n return __opts__.get('venafi', {}).get(\n 'base_url', 'https://api.venafi.cloud/v1'\n )\n",
"def _api_key():\n '''\n Return the API key\n '''\n return __opts__.get('venafi', {}).get('api_key', '')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
show_cert
|
python
|
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
|
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L550-L605
|
[
"def _base_url():\n '''\n Return the base_url\n '''\n return __opts__.get('venafi', {}).get(\n 'base_url', 'https://api.venafi.cloud/v1'\n )\n",
"def _api_key():\n '''\n Return the API key\n '''\n return __opts__.get('venafi', {}).get('api_key', '')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
list_domain_cache
|
python
|
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
|
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L629-L640
|
[
"def list(self, bank):\n '''\n Lists entries stored in the specified bank.\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :return:\n An iterable object containing all bank entries. Returns an empty\n iterator if the bank doesn't exists.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.list'.format(self.driver)\n return self.modules[fun](bank, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/runners/venafiapi.py
|
del_cached_domain
|
python
|
def del_cached_domain(domains):
'''
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
if isinstance(domains, six.string_types):
domains = domains.split(',')
if not isinstance(domains, list):
raise CommandExecutionError(
'You must pass in either a string containing one or more domains '
'separated by commas, or a list of single domain strings'
)
success = []
failed = []
for domain in domains:
try:
cache.flush('venafi/domains', domain)
success.append(domain)
except CommandExecutionError:
failed.append(domain)
return {'Succeeded': success, 'Failed': failed}
|
Delete cached domains from the master
CLI Example:
.. code-block:: bash
salt-run venafi.del_cached_domain domain1.example.com,domain2.example.com
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/venafiapi.py#L643-L669
|
[
"def flush(self, bank, key=None):\n '''\n Remove the key from the cache bank with all the key content. If no key is specified remove\n the entire bank with all keys and sub-banks inside.\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.flush'.format(self.driver)\n return self.modules[fun](bank, key=key, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Venafi
Before using this module you need to register an account with Venafi, and
configure it in your ``master`` configuration file.
First, you need to add a placeholder to the ``master`` file. This is because
the module will not load unless it finds an ``api_key`` setting, valid or not.
Open up ``/etc/salt/master`` and add:
.. code-block:: yaml
venafi:
api_key: None
Then register your email address with Venafi using the following command:
.. code-block:: bash
salt-run venafi.register <youremail@yourdomain.com>
This command will not return an ``api_key`` to you; that will be sent to you
via email from Venafi. Once you have received that key, open up your ``master``
file and set the ``api_key`` to it:
.. code-block:: yaml
venafi:
api_key: abcdef01-2345-6789-abcd-ef0123456789
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import tempfile
try:
from M2Crypto import RSA
HAS_M2 = True
except ImportError:
HAS_M2 = False
try:
from Cryptodome.PublicKey import RSA
except ImportError:
from Crypto.PublicKey import RSA
# Import Salt libs
import salt.cache
import salt.syspaths as syspaths
import salt.utils.files
import salt.utils.json
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError
# Import 3rd-party libs
from salt.ext import six
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
Only load the module if venafi is installed
'''
if __opts__.get('venafi', {}).get('api_key'):
return __virtualname__
return False
def _base_url():
'''
Return the base_url
'''
return __opts__.get('venafi', {}).get(
'base_url', 'https://api.venafi.cloud/v1'
)
def _api_key():
'''
Return the API key
'''
return __opts__.get('venafi', {}).get('api_key', '')
def gen_key(minion_id, dns_name=None, zone='default', password=None):
'''
Generate and return an private_key. If a ``dns_name`` is passed in, the
private_key will be cached under that name. The type of key and the
parameters used to generate the key are based on the default certificate
use policy associated with the specified zone.
CLI Example:
.. code-block:: bash
salt-run venafi.gen_key <minion_id> [dns_name] [zone] [password]
'''
# Get the default certificate use policy associated with the zone
# so we can generate keys that conform with policy
# The /v1/zones/tag/{name} API call is a shortcut to get the zoneID
# directly from the name
qdata = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
zone_id = qdata['dict']['id']
# the /v1/certificatepolicies?zoneId API call returns the default
# certificate use and certificate identity policies
qdata = __utils__['http.query'](
'{0}/certificatepolicies?zoneId={1}'.format(_base_url(), zone_id),
method='GET',
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
policies = qdata['dict']['certificatePolicies']
# Extract the key length and key type from the certificate use policy
# and generate the private key accordingly
for policy in policies:
if policy['certificatePolicyType'] == "CERTIFICATE_USE":
keyTypes = policy['keyTypes']
# in case multiple keytypes and key lengths are supported
# always use the first key type and key length
keygen_type = keyTypes[0]['keyType']
key_len = keyTypes[0]['keyLengths'][0]
if int(key_len) < 2048:
key_len = 2048
if keygen_type == "RSA":
if HAS_M2:
gen = RSA.gen_key(key_len, 65537)
private_key = gen.as_pem(cipher='des_ede3_cbc', callback=lambda x: six.b(password))
else:
gen = RSA.generate(bits=key_len)
private_key = gen.exportKey('PEM', password)
if dns_name is not None:
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
try:
data = cache.fetch(bank, dns_name)
data['private_key'] = private_key
data['minion_id'] = minion_id
except TypeError:
data = {'private_key': private_key,
'minion_id': minion_id}
cache.store(bank, dns_name, data)
return private_key
def gen_csr(
minion_id,
dns_name,
zone='default',
country=None,
state=None,
loc=None,
org=None,
org_unit=None,
password=None,
):
'''
Generate a csr using the host's private_key.
Analogous to:
.. code-block:: bash
VCert gencsr -cn [CN Value] -o "Beta Organization" -ou "Beta Group" \
-l "Palo Alto" -st "California" -c US
CLI Example:
.. code-block:: bash
salt-run venafi.gen_csr <minion_id> <dns_name>
'''
tmpdir = tempfile.mkdtemp()
os.chmod(tmpdir, 0o700)
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
if 'private_key' not in data:
data['private_key'] = gen_key(minion_id, dns_name, zone, password)
tmppriv = '{0}/priv'.format(tmpdir)
tmpcsr = '{0}/csr'.format(tmpdir)
with salt.utils.files.fopen(tmppriv, 'w') as if_:
if_.write(salt.utils.stringutils.to_str(data['private_key']))
if country is None:
country = __opts__.get('venafi', {}).get('country')
if state is None:
state = __opts__.get('venafi', {}).get('state')
if loc is None:
loc = __opts__.get('venafi', {}).get('loc')
if org is None:
org = __opts__.get('venafi', {}).get('org')
if org_unit is None:
org_unit = __opts__.get('venafi', {}).get('org_unit')
subject = '/C={0}/ST={1}/L={2}/O={3}/OU={4}/CN={5}'.format(
country,
state,
loc,
org,
org_unit,
dns_name,
)
cmd = "openssl req -new -sha256 -key {0} -out {1} -subj '{2}'".format(
tmppriv,
tmpcsr,
subject
)
if password is not None:
cmd += ' -passin pass:{0}'.format(password)
output = __salt__['salt.cmd']('cmd.run', cmd)
if 'problems making Certificate Request' in output:
raise CommandExecutionError(
'There was a problem generating the CSR. Please ensure that you '
'have the following variables set either on the command line, or '
'in the venafi section of your master configuration file: '
'country, state, loc, org, org_unit'
)
with salt.utils.files.fopen(tmpcsr, 'r') as of_:
csr = salt.utils.stringutils.to_unicode(of_.read())
data['minion_id'] = minion_id
data['csr'] = csr
cache.store(bank, dns_name, data)
return csr
def request(
minion_id,
dns_name=None,
zone='default',
request_id=None,
country='US',
state='California',
loc='Palo Alto',
org='Beta Organization',
org_unit='Beta Group',
password=None,
zone_id=None,
):
'''
Request a new certificate
Uses the following command:
.. code-block:: bash
VCert enroll -z <zone> -k <api key> -cn <domain name>
CLI Example:
.. code-block:: bash
salt-run venafi.request <minion_id> <dns_name>
'''
if password is not None:
if password.startswith('sdb://'):
password = __salt__['sdb.get'](password)
if zone_id is None:
zone_id = __opts__.get('venafi', {}).get('zone_id')
if zone_id is None and zone is not None:
zone_id = get_zone_id(zone)
if zone_id is None:
raise CommandExecutionError(
'Either a zone or a zone_id must be passed in or '
'configured in the master file. This id can be retreived using '
'venafi.show_company <domain>'
)
private_key = gen_key(minion_id, dns_name, zone, password)
csr = gen_csr(
minion_id,
dns_name,
zone=zone,
country=country,
state=state,
loc=loc,
org=org,
org_unit=org_unit,
password=password,
)
pdata = salt.utils.json.dumps({
'zoneId': zone_id,
'certificateSigningRequest': csr,
})
qdata = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
method='POST',
data=pdata,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
'Content-Type': 'application/json',
},
)
request_id = qdata['dict']['certificateRequests'][0]['id']
ret = {
'request_id': request_id,
'private_key': private_key,
'csr': csr,
'zone': zone,
}
bank = 'venafi/domains'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
data = cache.fetch(bank, dns_name)
if data is None:
data = {}
data.update({
'minion_id': minion_id,
'request_id': request_id,
'private_key': private_key,
'zone': zone,
'csr': csr,
})
cache.store(bank, dns_name, data)
_id_map(minion_id, dns_name)
return ret
# Request and renew are the same, so far as this module is concerned
renew = request
def _id_map(minion_id, dns_name):
'''
Maintain a relationship between a minion and a dns name
'''
bank = 'venafi/minions'
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
dns_names = cache.fetch(bank, minion_id)
if not isinstance(dns_names, list):
dns_names = []
if dns_name not in dns_names:
dns_names.append(dns_name)
cache.store(bank, minion_id, dns_names)
def register(email):
'''
Register a new user account
CLI Example:
.. code-block:: bash
salt-run venafi.register email@example.com
'''
data = __utils__['http.query'](
'{0}/useraccounts'.format(_base_url()),
method='POST',
data=salt.utils.json.dumps({
'username': email,
'userAccountType': 'API',
}),
status=True,
decode=True,
decode_type='json',
header_dict={
'Content-Type': 'application/json',
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_company(domain):
'''
Show company information, especially the company id
CLI Example:
.. code-block:: bash
salt-run venafi.show_company example.com
'''
data = __utils__['http.query'](
'{0}/companies/domain/{1}'.format(_base_url(), domain),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def show_csrs():
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_csrs
'''
data = __utils__['http.query'](
'{0}/certificaterequests'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data.get('dict', {})
def get_zone_id(zone_name):
'''
Get the zone ID for the given zone name
CLI Example:
.. code-block:: bash
salt-run venafi.get_zone_id default
'''
data = __utils__['http.query'](
'{0}/zones/tag/{1}'.format(_base_url(), zone_name),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']['id']
def show_policies():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/certificatepolicies'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_zones():
'''
Show zone details for the API key owner's company
CLI Example:
.. code-block:: bash
salt-run venafi.show_zones
'''
data = __utils__['http.query'](
'{0}/zones'.format(_base_url()),
status=True,
decode=True,
decode_type='json',
header_dict={
'tppl-api-key': _api_key(),
},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
return data['dict']
def show_cert(id_):
'''
Show certificate requests for this API key
CLI Example:
.. code-block:: bash
salt-run venafi.show_cert 01234567-89ab-cdef-0123-456789abcdef
'''
data = __utils__['http.query'](
'{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
params={
'format': 'PEM',
'chainOrder': 'ROOT_FIRST'
},
status=True,
text=True,
header_dict={'tppl-api-key': _api_key()},
)
status = data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(data['error'])
)
data = data.get('body', '')
csr_data = __utils__['http.query'](
'{0}/certificaterequests/{1}'.format(_base_url(), id_),
status=True,
decode=True,
decode_type='json',
header_dict={'tppl-api-key': _api_key()},
)
status = csr_data['status']
if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
raise CommandExecutionError(
'There was an API error: {0}'.format(csr_data['error'])
)
csr_data = csr_data.get('dict', {})
certs = _parse_certs(data)
dns_name = ''
for item in csr_data['certificateName'].split(','):
if item.startswith('cn='):
dns_name = item.split('=')[1]
#certs['CSR Data'] = csr_data
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
domain_data = cache.fetch('venafi/domains', dns_name)
if domain_data is None:
domain_data = {}
certs['private_key'] = domain_data.get('private_key')
domain_data.update(certs)
cache.store('venafi/domains', dns_name, domain_data)
certs['request_id'] = id_
return certs
pickup = show_cert
def show_rsa(minion_id, dns_name):
'''
Show a private RSA key
CLI Example:
.. code-block:: bash
salt-run venafi.show_rsa myminion domain.example.com
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
bank = 'venafi/domains'
data = cache.fetch(
bank, dns_name
)
return data['private_key']
def list_domain_cache():
'''
List domains that have been cached
CLI Example:
.. code-block:: bash
salt-run venafi.list_domain_cache
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
return cache.list('venafi/domains')
def _parse_certs(data):
cert_mode = False
cert = ''
certs = []
rsa_key = ''
for line in data.splitlines():
if not line.strip():
continue
if 'Successfully posted request' in line:
comps = line.split(' for ')
request_id = comps[-1].strip()
continue
if 'END CERTIFICATE' in line or 'END RSA private_key' in line:
if 'RSA' in line:
rsa_key = rsa_key + line
else:
cert = cert + line
certs.append(cert)
cert_mode = False
continue
if 'BEGIN CERTIFICATE' in line or 'BEGIN RSA private_key' in line:
if 'RSA' in line:
rsa_key = line + '\n'
else:
cert = line + '\n'
cert_mode = True
continue
if cert_mode is True:
cert = cert + line + '\n'
continue
rcert = certs.pop(0)
eecert = certs.pop(-1)
ret = {
'end_entity_certificate': eecert,
'private_key': rsa_key,
'root_certificate': rcert,
'intermediate_certificates': certs
}
return ret
|
saltstack/salt
|
salt/states/onyx.py
|
user_present
|
python
|
def user_present(name, password=None, roles=None, encrypted=False, crypt_salt=None, algorithm='sha256'):
'''
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
change_password = False
if password is not None:
change_password = not __salt__['onyx.cmd']('check_password', username=name,
password=password, encrypted=encrypted)
change_roles = False
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
change_roles = set(roles) != set(cur_roles)
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not any([change_password, change_roles, not old_user]):
ret['result'] = True
ret['comment'] = 'User already exists'
return ret
if change_roles is True:
remove_roles = set(cur_roles) - set(roles)
add_roles = set(roles) - set(cur_roles)
if __opts__['test'] is True:
ret['result'] = None
if not old_user:
ret['comment'] = 'User will be created'
if password is not None:
ret['changes']['password'] = True
if roles is not None:
ret['changes']['role'] = {'add': roles,
'remove': [], }
return ret
if change_password is True:
ret['comment'] = 'User will be updated'
ret['changes']['password'] = True
if change_roles is True:
ret['comment'] = 'User will be updated'
ret['changes']['roles'] = {'add': list(add_roles), 'remove': list(remove_roles)}
return ret
if change_password is True:
new_user = __salt__['onyx.cmd']('set_password', username=name, password=password,
encrypted=encrypted, role=roles[0] if roles else None,
crypt_salt=crypt_salt, algorithm=algorithm)
ret['changes']['password'] = {
'new': new_user,
'old': old_user,
}
if change_roles is True:
for role in add_roles:
__salt__['onyx.cmd']('set_role', username=name, role=role)
for role in remove_roles:
__salt__['onyx.cmd']('unset_role', username=name, role=role)
ret['changes']['roles'] = {
'new': __salt__['onyx.cmd']('get_roles', username=name),
'old': cur_roles,
}
correct_password = True
if password is not None:
correct_password = __salt__['onyx.cmd']('check_password', username=name, password=password,
encrypted=encrypted)
correct_roles = True
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
correct_roles = set(roles) != set(cur_roles)
if not correct_roles:
ret['comment'] = 'Failed to set correct roles'
elif not correct_password:
ret['comment'] = 'Failed to set correct password'
else:
ret['comment'] = 'User set correctly'
ret['result'] = True
return ret
|
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L18-L150
| null |
# -*- coding: utf-8 -*-
'''
State module for Onyx OS Switches Proxy minions
.. versionadded: Neon
For documentation on setting up the onyx proxy minion look in the documentation
for :mod:`salt.proxy.onyx<salt.proxy.onyx>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
def __virtual__():
return 'onyx.cmd' in __salt__
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not old_user:
ret['result'] = True
ret['comment'] = 'User does not exist'
return ret
if __opts__['test'] is True and old_user:
ret['result'] = None
ret['comment'] = 'User will be removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
__salt__['onyx.cmd']('remove_user', username=name)
if __salt__['onyx.cmd']('get_user', username=name):
ret['comment'] = 'Failed to remove user'
else:
ret['result'] = True
ret['comment'] = 'User removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('add_config', name)
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Successfully added config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to add config'
return ret
def config_absent(name):
'''
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Config is already absent'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be removed'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('delete_config', name)
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Successfully deleted config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to delete config'
return ret
def replace(name, repl, full_match=False):
'''
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
if full_match is False:
search = '^.*{0}.*$'.format(name)
else:
search = name
matches = __salt__['onyx.cmd']('find', search)
if not matches:
ret['result'] = True
ret['comment'] = 'Nothing found to replace'
return ret
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Configs will be changed'
ret['changes']['old'] = matches
ret['changes']['new'] = [re.sub(name, repl, match) for match in matches]
return ret
ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match)
matches = __salt__['onyx.cmd']('find', search)
if matches:
ret['result'] = False
ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl)
return ret
|
saltstack/salt
|
salt/states/onyx.py
|
user_absent
|
python
|
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not old_user:
ret['result'] = True
ret['comment'] = 'User does not exist'
return ret
if __opts__['test'] is True and old_user:
ret['result'] = None
ret['comment'] = 'User will be removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
__salt__['onyx.cmd']('remove_user', username=name)
if __salt__['onyx.cmd']('get_user', username=name):
ret['comment'] = 'Failed to remove user'
else:
ret['result'] = True
ret['comment'] = 'User removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
|
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L153-L197
| null |
# -*- coding: utf-8 -*-
'''
State module for Onyx OS Switches Proxy minions
.. versionadded: Neon
For documentation on setting up the onyx proxy minion look in the documentation
for :mod:`salt.proxy.onyx<salt.proxy.onyx>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
def __virtual__():
return 'onyx.cmd' in __salt__
def user_present(name, password=None, roles=None, encrypted=False, crypt_salt=None, algorithm='sha256'):
'''
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
change_password = False
if password is not None:
change_password = not __salt__['onyx.cmd']('check_password', username=name,
password=password, encrypted=encrypted)
change_roles = False
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
change_roles = set(roles) != set(cur_roles)
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not any([change_password, change_roles, not old_user]):
ret['result'] = True
ret['comment'] = 'User already exists'
return ret
if change_roles is True:
remove_roles = set(cur_roles) - set(roles)
add_roles = set(roles) - set(cur_roles)
if __opts__['test'] is True:
ret['result'] = None
if not old_user:
ret['comment'] = 'User will be created'
if password is not None:
ret['changes']['password'] = True
if roles is not None:
ret['changes']['role'] = {'add': roles,
'remove': [], }
return ret
if change_password is True:
ret['comment'] = 'User will be updated'
ret['changes']['password'] = True
if change_roles is True:
ret['comment'] = 'User will be updated'
ret['changes']['roles'] = {'add': list(add_roles), 'remove': list(remove_roles)}
return ret
if change_password is True:
new_user = __salt__['onyx.cmd']('set_password', username=name, password=password,
encrypted=encrypted, role=roles[0] if roles else None,
crypt_salt=crypt_salt, algorithm=algorithm)
ret['changes']['password'] = {
'new': new_user,
'old': old_user,
}
if change_roles is True:
for role in add_roles:
__salt__['onyx.cmd']('set_role', username=name, role=role)
for role in remove_roles:
__salt__['onyx.cmd']('unset_role', username=name, role=role)
ret['changes']['roles'] = {
'new': __salt__['onyx.cmd']('get_roles', username=name),
'old': cur_roles,
}
correct_password = True
if password is not None:
correct_password = __salt__['onyx.cmd']('check_password', username=name, password=password,
encrypted=encrypted)
correct_roles = True
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
correct_roles = set(roles) != set(cur_roles)
if not correct_roles:
ret['comment'] = 'Failed to set correct roles'
elif not correct_password:
ret['comment'] = 'Failed to set correct password'
else:
ret['comment'] = 'User set correctly'
ret['result'] = True
return ret
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('add_config', name)
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Successfully added config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to add config'
return ret
def config_absent(name):
'''
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Config is already absent'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be removed'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('delete_config', name)
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Successfully deleted config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to delete config'
return ret
def replace(name, repl, full_match=False):
'''
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
if full_match is False:
search = '^.*{0}.*$'.format(name)
else:
search = name
matches = __salt__['onyx.cmd']('find', search)
if not matches:
ret['result'] = True
ret['comment'] = 'Nothing found to replace'
return ret
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Configs will be changed'
ret['changes']['old'] = matches
ret['changes']['new'] = [re.sub(name, repl, match) for match in matches]
return ret
ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match)
matches = __salt__['onyx.cmd']('find', search)
if matches:
ret['result'] = False
ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl)
return ret
|
saltstack/salt
|
salt/states/onyx.py
|
config_present
|
python
|
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('add_config', name)
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Successfully added config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to add config'
return ret
|
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L200-L250
| null |
# -*- coding: utf-8 -*-
'''
State module for Onyx OS Switches Proxy minions
.. versionadded: Neon
For documentation on setting up the onyx proxy minion look in the documentation
for :mod:`salt.proxy.onyx<salt.proxy.onyx>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
def __virtual__():
return 'onyx.cmd' in __salt__
def user_present(name, password=None, roles=None, encrypted=False, crypt_salt=None, algorithm='sha256'):
'''
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
change_password = False
if password is not None:
change_password = not __salt__['onyx.cmd']('check_password', username=name,
password=password, encrypted=encrypted)
change_roles = False
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
change_roles = set(roles) != set(cur_roles)
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not any([change_password, change_roles, not old_user]):
ret['result'] = True
ret['comment'] = 'User already exists'
return ret
if change_roles is True:
remove_roles = set(cur_roles) - set(roles)
add_roles = set(roles) - set(cur_roles)
if __opts__['test'] is True:
ret['result'] = None
if not old_user:
ret['comment'] = 'User will be created'
if password is not None:
ret['changes']['password'] = True
if roles is not None:
ret['changes']['role'] = {'add': roles,
'remove': [], }
return ret
if change_password is True:
ret['comment'] = 'User will be updated'
ret['changes']['password'] = True
if change_roles is True:
ret['comment'] = 'User will be updated'
ret['changes']['roles'] = {'add': list(add_roles), 'remove': list(remove_roles)}
return ret
if change_password is True:
new_user = __salt__['onyx.cmd']('set_password', username=name, password=password,
encrypted=encrypted, role=roles[0] if roles else None,
crypt_salt=crypt_salt, algorithm=algorithm)
ret['changes']['password'] = {
'new': new_user,
'old': old_user,
}
if change_roles is True:
for role in add_roles:
__salt__['onyx.cmd']('set_role', username=name, role=role)
for role in remove_roles:
__salt__['onyx.cmd']('unset_role', username=name, role=role)
ret['changes']['roles'] = {
'new': __salt__['onyx.cmd']('get_roles', username=name),
'old': cur_roles,
}
correct_password = True
if password is not None:
correct_password = __salt__['onyx.cmd']('check_password', username=name, password=password,
encrypted=encrypted)
correct_roles = True
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
correct_roles = set(roles) != set(cur_roles)
if not correct_roles:
ret['comment'] = 'Failed to set correct roles'
elif not correct_password:
ret['comment'] = 'Failed to set correct password'
else:
ret['comment'] = 'User set correctly'
ret['result'] = True
return ret
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not old_user:
ret['result'] = True
ret['comment'] = 'User does not exist'
return ret
if __opts__['test'] is True and old_user:
ret['result'] = None
ret['comment'] = 'User will be removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
__salt__['onyx.cmd']('remove_user', username=name)
if __salt__['onyx.cmd']('get_user', username=name):
ret['comment'] = 'Failed to remove user'
else:
ret['result'] = True
ret['comment'] = 'User removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
def config_absent(name):
'''
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Config is already absent'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be removed'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('delete_config', name)
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Successfully deleted config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to delete config'
return ret
def replace(name, repl, full_match=False):
'''
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
if full_match is False:
search = '^.*{0}.*$'.format(name)
else:
search = name
matches = __salt__['onyx.cmd']('find', search)
if not matches:
ret['result'] = True
ret['comment'] = 'Nothing found to replace'
return ret
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Configs will be changed'
ret['changes']['old'] = matches
ret['changes']['new'] = [re.sub(name, repl, match) for match in matches]
return ret
ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match)
matches = __salt__['onyx.cmd']('find', search)
if matches:
ret['result'] = False
ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl)
return ret
|
saltstack/salt
|
salt/states/onyx.py
|
config_absent
|
python
|
def config_absent(name):
'''
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Config is already absent'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be removed'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('delete_config', name)
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Successfully deleted config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to delete config'
return ret
|
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L253-L304
| null |
# -*- coding: utf-8 -*-
'''
State module for Onyx OS Switches Proxy minions
.. versionadded: Neon
For documentation on setting up the onyx proxy minion look in the documentation
for :mod:`salt.proxy.onyx<salt.proxy.onyx>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
def __virtual__():
return 'onyx.cmd' in __salt__
def user_present(name, password=None, roles=None, encrypted=False, crypt_salt=None, algorithm='sha256'):
'''
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
change_password = False
if password is not None:
change_password = not __salt__['onyx.cmd']('check_password', username=name,
password=password, encrypted=encrypted)
change_roles = False
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
change_roles = set(roles) != set(cur_roles)
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not any([change_password, change_roles, not old_user]):
ret['result'] = True
ret['comment'] = 'User already exists'
return ret
if change_roles is True:
remove_roles = set(cur_roles) - set(roles)
add_roles = set(roles) - set(cur_roles)
if __opts__['test'] is True:
ret['result'] = None
if not old_user:
ret['comment'] = 'User will be created'
if password is not None:
ret['changes']['password'] = True
if roles is not None:
ret['changes']['role'] = {'add': roles,
'remove': [], }
return ret
if change_password is True:
ret['comment'] = 'User will be updated'
ret['changes']['password'] = True
if change_roles is True:
ret['comment'] = 'User will be updated'
ret['changes']['roles'] = {'add': list(add_roles), 'remove': list(remove_roles)}
return ret
if change_password is True:
new_user = __salt__['onyx.cmd']('set_password', username=name, password=password,
encrypted=encrypted, role=roles[0] if roles else None,
crypt_salt=crypt_salt, algorithm=algorithm)
ret['changes']['password'] = {
'new': new_user,
'old': old_user,
}
if change_roles is True:
for role in add_roles:
__salt__['onyx.cmd']('set_role', username=name, role=role)
for role in remove_roles:
__salt__['onyx.cmd']('unset_role', username=name, role=role)
ret['changes']['roles'] = {
'new': __salt__['onyx.cmd']('get_roles', username=name),
'old': cur_roles,
}
correct_password = True
if password is not None:
correct_password = __salt__['onyx.cmd']('check_password', username=name, password=password,
encrypted=encrypted)
correct_roles = True
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
correct_roles = set(roles) != set(cur_roles)
if not correct_roles:
ret['comment'] = 'Failed to set correct roles'
elif not correct_password:
ret['comment'] = 'Failed to set correct password'
else:
ret['comment'] = 'User set correctly'
ret['result'] = True
return ret
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not old_user:
ret['result'] = True
ret['comment'] = 'User does not exist'
return ret
if __opts__['test'] is True and old_user:
ret['result'] = None
ret['comment'] = 'User will be removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
__salt__['onyx.cmd']('remove_user', username=name)
if __salt__['onyx.cmd']('get_user', username=name):
ret['comment'] = 'Failed to remove user'
else:
ret['result'] = True
ret['comment'] = 'User removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('add_config', name)
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Successfully added config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to add config'
return ret
def replace(name, repl, full_match=False):
'''
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
if full_match is False:
search = '^.*{0}.*$'.format(name)
else:
search = name
matches = __salt__['onyx.cmd']('find', search)
if not matches:
ret['result'] = True
ret['comment'] = 'Nothing found to replace'
return ret
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Configs will be changed'
ret['changes']['old'] = matches
ret['changes']['new'] = [re.sub(name, repl, match) for match in matches]
return ret
ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match)
matches = __salt__['onyx.cmd']('find', search)
if matches:
ret['result'] = False
ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl)
return ret
|
saltstack/salt
|
salt/states/onyx.py
|
replace
|
python
|
def replace(name, repl, full_match=False):
'''
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
if full_match is False:
search = '^.*{0}.*$'.format(name)
else:
search = name
matches = __salt__['onyx.cmd']('find', search)
if not matches:
ret['result'] = True
ret['comment'] = 'Nothing found to replace'
return ret
if __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Configs will be changed'
ret['changes']['old'] = matches
ret['changes']['new'] = [re.sub(name, repl, match) for match in matches]
return ret
ret['changes'] = __salt__['onyx.cmd']('replace', name, repl, full_match=full_match)
matches = __salt__['onyx.cmd']('find', search)
if matches:
ret['result'] = False
ret['comment'] = 'Failed to replace all instances of "{0}"'.format(name)
else:
ret['result'] = True
ret['comment'] = 'Successfully replaced all instances of "{0}" with "{1}"'.format(name, repl)
return ret
|
Replace all instances of a string or full line in the running config
name
String to replace
repl
The replacement text
full_match
Whether `name` will match the full line or only a subset of the line.
Defaults to False. When False, .* is added around `name` for matching
in the `show run` config.
Examples:
.. code-block:: yaml
replace snmp string:
onyx.replace:
- name: randoSNMPstringHERE
- repl: NEWrandoSNMPstringHERE
replace full snmp string:
onyx.replace:
- name: ^snmp-server community randoSNMPstringHERE group network-operator$
- repl: snmp-server community NEWrandoSNMPstringHERE group network-operator
- full_match: True
.. note::
The first example will replace the SNMP string on both the group and
the ACL, so you will not lose the ACL setting. Because the second is
an exact match of the line, when the group is removed, the ACL is
removed, but not readded, because it was not matched.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/onyx.py#L307-L379
| null |
# -*- coding: utf-8 -*-
'''
State module for Onyx OS Switches Proxy minions
.. versionadded: Neon
For documentation on setting up the onyx proxy minion look in the documentation
for :mod:`salt.proxy.onyx<salt.proxy.onyx>`.
'''
from __future__ import absolute_import, print_function, unicode_literals
import re
def __virtual__():
return 'onyx.cmd' in __salt__
def user_present(name, password=None, roles=None, encrypted=False, crypt_salt=None, algorithm='sha256'):
'''
Ensure a user is present with the specified groups
name
Name of user
password
Encrypted or Plain Text password for user
roles
List of roles the user should be assigned. Any roles not in this list will be removed
encrypted
Whether the password is encrypted already or not. Defaults to False
crypt_salt
Salt to use when encrypting the password. Default is None (salt is
randomly generated for unhashed passwords)
algorithm
Algorithm to use for hashing password. Defaults to sha256.
Accepts md5, blowfish, sha256, sha512
.. note: sha512 may make the hash too long to save in NX OS which limits the has to 64 characters
Examples:
.. code-block:: yaml
create:
onyx.user_present:
- name: daniel
- roles:
- vdc-admin
set_password:
onyx.user_present:
- name: daniel
- password: admin
- roles:
- network-admin
update:
onyx.user_present:
- name: daniel
- password: AiN9jaoP
- roles:
- network-admin
- vdc-admin
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
change_password = False
if password is not None:
change_password = not __salt__['onyx.cmd']('check_password', username=name,
password=password, encrypted=encrypted)
change_roles = False
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
change_roles = set(roles) != set(cur_roles)
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not any([change_password, change_roles, not old_user]):
ret['result'] = True
ret['comment'] = 'User already exists'
return ret
if change_roles is True:
remove_roles = set(cur_roles) - set(roles)
add_roles = set(roles) - set(cur_roles)
if __opts__['test'] is True:
ret['result'] = None
if not old_user:
ret['comment'] = 'User will be created'
if password is not None:
ret['changes']['password'] = True
if roles is not None:
ret['changes']['role'] = {'add': roles,
'remove': [], }
return ret
if change_password is True:
ret['comment'] = 'User will be updated'
ret['changes']['password'] = True
if change_roles is True:
ret['comment'] = 'User will be updated'
ret['changes']['roles'] = {'add': list(add_roles), 'remove': list(remove_roles)}
return ret
if change_password is True:
new_user = __salt__['onyx.cmd']('set_password', username=name, password=password,
encrypted=encrypted, role=roles[0] if roles else None,
crypt_salt=crypt_salt, algorithm=algorithm)
ret['changes']['password'] = {
'new': new_user,
'old': old_user,
}
if change_roles is True:
for role in add_roles:
__salt__['onyx.cmd']('set_role', username=name, role=role)
for role in remove_roles:
__salt__['onyx.cmd']('unset_role', username=name, role=role)
ret['changes']['roles'] = {
'new': __salt__['onyx.cmd']('get_roles', username=name),
'old': cur_roles,
}
correct_password = True
if password is not None:
correct_password = __salt__['onyx.cmd']('check_password', username=name, password=password,
encrypted=encrypted)
correct_roles = True
if roles is not None:
cur_roles = __salt__['onyx.cmd']('get_roles', username=name)
correct_roles = set(roles) != set(cur_roles)
if not correct_roles:
ret['comment'] = 'Failed to set correct roles'
elif not correct_password:
ret['comment'] = 'Failed to set correct password'
else:
ret['comment'] = 'User set correctly'
ret['result'] = True
return ret
def user_absent(name):
'''
Ensure a user is not present
name
username to remove if it exists
Examples:
.. code-block:: yaml
delete:
onyx.user_absent:
- name: daniel
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
old_user = __salt__['onyx.cmd']('get_user', username=name)
if not old_user:
ret['result'] = True
ret['comment'] = 'User does not exist'
return ret
if __opts__['test'] is True and old_user:
ret['result'] = None
ret['comment'] = 'User will be removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
__salt__['onyx.cmd']('remove_user', username=name)
if __salt__['onyx.cmd']('get_user', username=name):
ret['comment'] = 'Failed to remove user'
else:
ret['result'] = True
ret['comment'] = 'User removed'
ret['changes']['old'] = old_user
ret['changes']['new'] = ''
return ret
def config_present(name):
'''
Ensure a specific configuration line exists in the running config
name
config line to set
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
add snmp acl:
onyx.config_present:
- names:
- snmp-server community randoSNMPstringHERE use-acl snmp-acl-ro
- snmp-server community AnotherRandomSNMPSTring use-acl snmp-acl-rw
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Config is already set'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be added'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('add_config', name)
matches = __salt__['onyx.cmd']('find', name)
if matches:
ret['result'] = True
ret['comment'] = 'Successfully added config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to add config'
return ret
def config_absent(name):
'''
Ensure a specific configuration line does not exist in the running config
name
config line to remove
Examples:
.. code-block:: yaml
add snmp group:
onyx.config_absent:
- names:
- snmp-server community randoSNMPstringHERE group network-operator
- snmp-server community AnotherRandomSNMPSTring group network-admin
.. note::
For certain cases extra lines could be removed based on dependencies.
In this example, included after the example for config_present, the
ACLs would be removed because they depend on the existence of the
group.
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Config is already absent'
elif __opts__['test'] is True:
ret['result'] = None
ret['comment'] = 'Config will be removed'
ret['changes']['new'] = name
else:
__salt__['onyx.cmd']('delete_config', name)
matches = __salt__['onyx.cmd']('find', name)
if not matches:
ret['result'] = True
ret['comment'] = 'Successfully deleted config'
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to delete config'
return ret
|
saltstack/salt
|
salt/states/mssql_login.py
|
present
|
python
|
def present(name, password=None, domain=None, server_roles=None, options=None, **kwargs):
'''
Checks existance of the named login.
If not present, creates the login with the specified roles and options.
name
The name of the login to manage
password
Creates a SQL Server authentication login
Since hashed passwords are varbinary values, if the
new_login_password is 'long', it will be considered
to be HASHED.
domain
Creates a Windows authentication login.
Needs to be NetBIOS domain or hostname
server_roles
Add this login to all the server roles in the list
options
Can be a list of strings, a dictionary, or a list of dictionaries
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if bool(password) == bool(domain):
ret['result'] = False
ret['comment'] = 'One and only one of password and domain should be specifies'
return ret
if __salt__['mssql.login_exists'](name, domain=domain, **kwargs):
ret['comment'] = 'Login {0} is already present (Not going to try to set its password)'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Login {0} is set to be added'.format(name)
return ret
login_created = __salt__['mssql.login_create'](name,
new_login_password=password,
new_login_domain=domain,
new_login_roles=server_roles,
new_login_options=_normalize_options(options),
**kwargs)
# Non-empty strings are also evaluated to True, so we cannot use if not login_created:
if login_created is not True:
ret['result'] = False
ret['comment'] = 'Login {0} failed to be added: {1}'.format(name, login_created)
return ret
ret['comment'] = 'Login {0} has been added. '.format(name)
ret['changes'][name] = 'Present'
return ret
|
Checks existance of the named login.
If not present, creates the login with the specified roles and options.
name
The name of the login to manage
password
Creates a SQL Server authentication login
Since hashed passwords are varbinary values, if the
new_login_password is 'long', it will be considered
to be HASHED.
domain
Creates a Windows authentication login.
Needs to be NetBIOS domain or hostname
server_roles
Add this login to all the server roles in the list
options
Can be a list of strings, a dictionary, or a list of dictionaries
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_login.py#L37-L87
|
[
"def _normalize_options(options):\n if type(options) in [dict, collections.OrderedDict]:\n return ['{0}={1}'.format(k, v) for k, v in options.items()]\n if type(options) is list and (not options or type(options[0]) is str):\n return options\n # Invalid options\n if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:\n return []\n return [o for d in options for o in _normalize_options(d)]\n"
] |
# -*- coding: utf-8 -*-
'''
Management of Microsoft SQLServer Logins
========================================
The mssql_login module is used to create
and manage SQL Server Logins
.. code-block:: yaml
frank:
mssql_login.present
- domain: mydomain
'''
from __future__ import absolute_import, print_function, unicode_literals
import collections
def __virtual__():
'''
Only load if the mssql module is present
'''
return 'mssql.version' in __salt__
def _normalize_options(options):
if type(options) in [dict, collections.OrderedDict]:
return ['{0}={1}'.format(k, v) for k, v in options.items()]
if type(options) is list and (not options or type(options[0]) is str):
return options
# Invalid options
if type(options) is not list or type(options[0]) not in [dict, collections.OrderedDict]:
return []
return [o for d in options for o in _normalize_options(d)]
def absent(name, **kwargs):
'''
Ensure that the named login is absent
name
The name of the login to remove
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if not __salt__['mssql.login_exists'](name):
ret['comment'] = 'Login {0} is not present'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Login {0} is set to be removed'.format(name)
return ret
if __salt__['mssql.login_remove'](name, **kwargs):
ret['comment'] = 'Login {0} has been removed'.format(name)
ret['changes'][name] = 'Absent'
return ret
# else:
ret['result'] = False
ret['comment'] = 'Login {0} failed to be removed'.format(name)
return ret
|
saltstack/salt
|
salt/states/cmd.py
|
_reinterpreted_state
|
python
|
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
|
Re-interpret the state returned by salt.state.run using our protocol.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L251-L310
| null |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
mod_run_check
|
python
|
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
|
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L327-L398
| null |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
wait
|
python
|
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
|
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L401-L554
| null |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
wait_script
|
python
|
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
|
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L561-L710
| null |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
run
|
python
|
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
|
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L713-L1005
|
[
"def warn_until(version,\n message,\n category=DeprecationWarning,\n stacklevel=None,\n _version_info_=None,\n _dont_call_warnings=False):\n '''\n Helper function to raise a warning, by default, a ``DeprecationWarning``,\n until the provided ``version``, after which, a ``RuntimeError`` will\n be raised to remind the developers to remove the warning because the\n target version has been reached.\n\n :param version: The version info or name after which the warning becomes a\n ``RuntimeError``. For example ``(0, 17)`` or ``Hydrogen``\n or an instance of :class:`salt.version.SaltStackVersion`.\n :param message: The warning message to be displayed.\n :param category: The warning class to be thrown, by default\n ``DeprecationWarning``\n :param stacklevel: There should be no need to set the value of\n ``stacklevel``. Salt should be able to do the right thing.\n :param _version_info_: In order to reuse this function for other SaltStack\n projects, they need to be able to provide the\n version info to compare to.\n :param _dont_call_warnings: This parameter is used just to get the\n functionality until the actual error is to be\n issued. When we're only after the salt version\n checks to raise a ``RuntimeError``.\n '''\n if not isinstance(version, (tuple,\n six.string_types,\n salt.version.SaltStackVersion)):\n raise RuntimeError(\n 'The \\'version\\' argument should be passed as a tuple, string or '\n 'an instance of \\'salt.version.SaltStackVersion\\'.'\n )\n elif isinstance(version, tuple):\n version = salt.version.SaltStackVersion(*version)\n elif isinstance(version, six.string_types):\n version = salt.version.SaltStackVersion.from_name(version)\n\n if stacklevel is None:\n # Attribute the warning to the calling function, not to warn_until()\n stacklevel = 2\n\n if _version_info_ is None:\n _version_info_ = salt.version.__version_info__\n\n _version_ = salt.version.SaltStackVersion(*_version_info_)\n\n if _version_ >= version:\n import inspect\n caller = inspect.getframeinfo(sys._getframe(stacklevel - 1))\n raise RuntimeError(\n 'The warning triggered on filename \\'{filename}\\', line number '\n '{lineno}, is supposed to be shown until version '\n '{until_version} is released. Current version is now '\n '{salt_version}. Please remove the warning.'.format(\n filename=caller.filename,\n lineno=caller.lineno,\n until_version=version.formatted_version,\n salt_version=_version_.formatted_version\n ),\n )\n\n if _dont_call_warnings is False:\n def _formatwarning(message,\n category,\n filename,\n lineno,\n line=None): # pylint: disable=W0613\n '''\n Replacement for warnings.formatwarning that disables the echoing of\n the 'line' parameter.\n '''\n return '{0}:{1}: {2}: {3}\\n'.format(\n filename, lineno, category.__name__, message\n )\n saved = warnings.formatwarning\n warnings.formatwarning = _formatwarning\n warnings.warn(\n message.format(version=version.formatted_version),\n category,\n stacklevel=stacklevel\n )\n warnings.formatwarning = saved\n",
"def _reinterpreted_state(state):\n '''\n Re-interpret the state returned by salt.state.run using our protocol.\n '''\n ret = state['changes']\n state['changes'] = {}\n state['comment'] = ''\n\n out = ret.get('stdout')\n if not out:\n if ret.get('stderr'):\n state['comment'] = ret['stderr']\n return state\n\n is_json = False\n try:\n data = salt.utils.json.loads(out)\n if not isinstance(data, dict):\n return _failout(\n state,\n 'script JSON output must be a JSON object (e.g., {})!'\n )\n is_json = True\n except ValueError:\n idx = out.rstrip().rfind('\\n')\n if idx != -1:\n out = out[idx + 1:]\n data = {}\n try:\n for item in salt.utils.args.shlex_split(out):\n key, val = item.split('=')\n data[key] = val\n except ValueError:\n state = _failout(\n state,\n 'Failed parsing script output! '\n 'Stdout must be JSON or a line of name=value pairs.'\n )\n state['changes'].update(ret)\n return state\n\n changed = _is_true(data.get('changed', 'no'))\n\n if 'comment' in data:\n state['comment'] = data['comment']\n del data['comment']\n\n if changed:\n for key in ret:\n data.setdefault(key, ret[key])\n\n # if stdout is the state output in JSON, don't show it.\n # otherwise it contains the one line name=value pairs, strip it.\n data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]\n state['changes'] = data\n\n #FIXME: if it's not changed but there's stdout and/or stderr then those\n # won't be shown as the function output. (though, they will be shown\n # inside INFO logs).\n return state\n",
"def mod_run_check(cmd_kwargs, onlyif, unless, creates):\n '''\n Execute the onlyif and unless logic.\n Return a result dict if:\n * onlyif failed (onlyif != 0)\n * unless succeeded (unless == 0)\n else return True\n '''\n # never use VT for onlyif/unless executions because this will lead\n # to quote problems\n cmd_kwargs = copy.deepcopy(cmd_kwargs)\n cmd_kwargs['use_vt'] = False\n cmd_kwargs['bg'] = False\n\n if onlyif is not None:\n if isinstance(onlyif, six.string_types):\n cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(onlyif, list):\n for entry in onlyif:\n cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command \\'%s\\' return code: %s', entry, cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false: {0}'.format(entry),\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(onlyif, six.string_types):\n if not onlyif:\n log.debug('Command not run: onlyif did not evaluate to string_type')\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n\n if unless is not None:\n if isinstance(unless, six.string_types):\n cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd == 0:\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(unless, list):\n cmd = []\n for entry in unless:\n cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))\n log.debug('Last command return code: %s', cmd)\n if all([c == 0 for c in cmd]):\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(unless, six.string_types):\n if unless:\n log.debug('Command not run: unless did not evaluate to string_type')\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n\n if isinstance(creates, six.string_types) and os.path.exists(creates):\n return {'comment': '{0} exists'.format(creates),\n 'result': True}\n elif isinstance(creates, list) and all([\n os.path.exists(path) for path in creates\n ]):\n return {'comment': 'All files in creates exist',\n 'result': True}\n\n # No reason to stop, return True\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
script
|
python
|
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
|
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L1008-L1292
|
[
"def _reinterpreted_state(state):\n '''\n Re-interpret the state returned by salt.state.run using our protocol.\n '''\n ret = state['changes']\n state['changes'] = {}\n state['comment'] = ''\n\n out = ret.get('stdout')\n if not out:\n if ret.get('stderr'):\n state['comment'] = ret['stderr']\n return state\n\n is_json = False\n try:\n data = salt.utils.json.loads(out)\n if not isinstance(data, dict):\n return _failout(\n state,\n 'script JSON output must be a JSON object (e.g., {})!'\n )\n is_json = True\n except ValueError:\n idx = out.rstrip().rfind('\\n')\n if idx != -1:\n out = out[idx + 1:]\n data = {}\n try:\n for item in salt.utils.args.shlex_split(out):\n key, val = item.split('=')\n data[key] = val\n except ValueError:\n state = _failout(\n state,\n 'Failed parsing script output! '\n 'Stdout must be JSON or a line of name=value pairs.'\n )\n state['changes'].update(ret)\n return state\n\n changed = _is_true(data.get('changed', 'no'))\n\n if 'comment' in data:\n state['comment'] = data['comment']\n del data['comment']\n\n if changed:\n for key in ret:\n data.setdefault(key, ret[key])\n\n # if stdout is the state output in JSON, don't show it.\n # otherwise it contains the one line name=value pairs, strip it.\n data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]\n state['changes'] = data\n\n #FIXME: if it's not changed but there's stdout and/or stderr then those\n # won't be shown as the function output. (though, they will be shown\n # inside INFO logs).\n return state\n",
"def mod_run_check(cmd_kwargs, onlyif, unless, creates):\n '''\n Execute the onlyif and unless logic.\n Return a result dict if:\n * onlyif failed (onlyif != 0)\n * unless succeeded (unless == 0)\n else return True\n '''\n # never use VT for onlyif/unless executions because this will lead\n # to quote problems\n cmd_kwargs = copy.deepcopy(cmd_kwargs)\n cmd_kwargs['use_vt'] = False\n cmd_kwargs['bg'] = False\n\n if onlyif is not None:\n if isinstance(onlyif, six.string_types):\n cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(onlyif, list):\n for entry in onlyif:\n cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command \\'%s\\' return code: %s', entry, cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false: {0}'.format(entry),\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(onlyif, six.string_types):\n if not onlyif:\n log.debug('Command not run: onlyif did not evaluate to string_type')\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n\n if unless is not None:\n if isinstance(unless, six.string_types):\n cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd == 0:\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(unless, list):\n cmd = []\n for entry in unless:\n cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))\n log.debug('Last command return code: %s', cmd)\n if all([c == 0 for c in cmd]):\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(unless, six.string_types):\n if unless:\n log.debug('Command not run: unless did not evaluate to string_type')\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n\n if isinstance(creates, six.string_types) and os.path.exists(creates):\n return {'comment': '{0} exists'.format(creates),\n 'result': True}\n elif isinstance(creates, list) and all([\n os.path.exists(path) for path in creates\n ]):\n return {'comment': 'All files in creates exist',\n 'result': True}\n\n # No reason to stop, return True\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
call
|
python
|
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
|
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L1295-L1369
|
[
"def mod_run_check(cmd_kwargs, onlyif, unless, creates):\n '''\n Execute the onlyif and unless logic.\n Return a result dict if:\n * onlyif failed (onlyif != 0)\n * unless succeeded (unless == 0)\n else return True\n '''\n # never use VT for onlyif/unless executions because this will lead\n # to quote problems\n cmd_kwargs = copy.deepcopy(cmd_kwargs)\n cmd_kwargs['use_vt'] = False\n cmd_kwargs['bg'] = False\n\n if onlyif is not None:\n if isinstance(onlyif, six.string_types):\n cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(onlyif, list):\n for entry in onlyif:\n cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command \\'%s\\' return code: %s', entry, cmd)\n if cmd != 0:\n return {'comment': 'onlyif condition is false: {0}'.format(entry),\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(onlyif, six.string_types):\n if not onlyif:\n log.debug('Command not run: onlyif did not evaluate to string_type')\n return {'comment': 'onlyif condition is false',\n 'skip_watch': True,\n 'result': True}\n\n if unless is not None:\n if isinstance(unless, six.string_types):\n cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)\n log.debug('Last command return code: %s', cmd)\n if cmd == 0:\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif isinstance(unless, list):\n cmd = []\n for entry in unless:\n cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))\n log.debug('Last command return code: %s', cmd)\n if all([c == 0 for c in cmd]):\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n elif not isinstance(unless, six.string_types):\n if unless:\n log.debug('Command not run: unless did not evaluate to string_type')\n return {'comment': 'unless condition is true',\n 'skip_watch': True,\n 'result': True}\n\n if isinstance(creates, six.string_types) and os.path.exists(creates):\n return {'comment': '{0} exists'.format(creates),\n 'result': True}\n elif isinstance(creates, list) and all([\n os.path.exists(path) for path in creates\n ]):\n return {'comment': 'All files in creates exist',\n 'result': True}\n\n # No reason to stop, return True\n return True\n",
"def func():\n '''\n Mock func method\n '''\n if flag:\n return {}\n else:\n return []\n"
] |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
saltstack/salt
|
salt/states/cmd.py
|
mod_watch
|
python
|
def mod_watch(name, **kwargs):
'''
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
if kwargs['sfun'] in ('wait', 'run', 'watch'):
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(run(name, **kwargs))
return run(name, **kwargs)
elif kwargs['sfun'] == 'wait_script' or kwargs['sfun'] == 'script':
if kwargs.get('stateful'):
kwargs.pop('stateful')
return _reinterpreted_state(script(name, **kwargs))
return script(name, **kwargs)
elif kwargs['sfun'] == 'wait_call' or kwargs['sfun'] == 'call':
if kwargs.get('func'):
func = kwargs.pop('func')
return call(name, func, **kwargs)
else:
return {'name': name,
'changes': {},
'comment': (
'cmd.{0[sfun]} needs a named parameter func'
).format(kwargs),
'result': False}
return {'name': name,
'changes': {},
'comment': 'cmd.{0[sfun]} does not work with the watch requisite, '
'please use cmd.wait or cmd.wait_script'.format(kwargs),
'result': False}
|
Execute a cmd function based on a watch call
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cmd.py#L1391-L1429
|
[
"def script(name,\n source=None,\n template=None,\n onlyif=None,\n unless=None,\n creates=None,\n cwd=None,\n runas=None,\n shell=None,\n env=None,\n stateful=False,\n umask=None,\n timeout=None,\n use_vt=False,\n output_loglevel='debug',\n hide_output=False,\n defaults=None,\n context=None,\n success_retcodes=None,\n success_stdout=None,\n success_stderr=None,\n **kwargs):\n '''\n Download a script and execute it with specified arguments.\n\n source\n The location of the script to download. If the file is located on the\n master in the directory named spam, and is called eggs, the source\n string is salt://spam/eggs\n\n template\n If this setting is applied then the named templating engine will be\n used to render the downloaded file. Currently jinja, mako, and wempy\n are supported\n\n name\n Either \"cmd arg1 arg2 arg3...\" (cmd is not used) or a source\n \"salt://...\".\n\n onlyif\n Run the named command only if the command passed to the ``onlyif``\n option returns true\n\n unless\n Run the named command only if the command passed to the ``unless``\n option returns false\n\n cwd\n The current working directory to execute the command in, defaults to\n /root\n\n runas\n The name of the user to run the command as\n\n shell\n The shell to use for execution. The default is set in grains['shell']\n\n env\n A list of environment variables to be set prior to execution.\n Example:\n\n .. code-block:: yaml\n\n salt://scripts/foo.sh:\n cmd.script:\n - env:\n - BATCH: 'yes'\n\n .. warning::\n\n The above illustrates a common PyYAML pitfall, that **yes**,\n **no**, **on**, **off**, **true**, and **false** are all loaded as\n boolean ``True`` and ``False`` values, and must be enclosed in\n quotes to be used as strings. More info on this (and other) PyYAML\n idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.\n\n Variables as values are not evaluated. So $PATH in the following\n example is a literal '$PATH':\n\n .. code-block:: yaml\n\n salt://scripts/bar.sh:\n cmd.script:\n - env: \"PATH=/some/path:$PATH\"\n\n One can still use the existing $PATH by using a bit of Jinja:\n\n .. code-block:: jinja\n\n {% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}\n\n mycommand:\n cmd.run:\n - name: ls -l /\n - env:\n - PATH: {{ [current_path, '/my/special/bin']|join(':') }}\n\n saltenv : ``base``\n The Salt environment to use\n\n umask\n The umask (in octal) to use when running the command.\n\n stateful\n The command being executed is expected to return data about executing\n a state. For more information, see the :ref:`stateful-argument` section.\n\n timeout\n If the command has not terminated after timeout seconds, send the\n subprocess sigterm, and if sigterm is ignored, follow up with sigkill\n\n args\n String of command line args to pass to the script. Only used if no\n args are specified as part of the `name` argument. To pass a string\n containing spaces in YAML, you will need to doubly-quote it: \"arg1\n 'arg two' arg3\"\n\n creates\n Only run if the file specified by ``creates`` do not exist. If you\n specify a list of files then this state will only run if **any** of\n the files does not exist.\n\n .. versionadded:: 2014.7.0\n\n use_vt\n Use VT utils (saltstack) to stream the command output more\n interactively to the console and the logs.\n This is experimental.\n\n context\n .. versionadded:: 2016.3.0\n\n Overrides default context variables passed to the template.\n\n defaults\n .. versionadded:: 2016.3.0\n\n Default context passed to the template.\n\n output_loglevel : debug\n Control the loglevel at which the output from the command is logged to\n the minion log.\n\n .. note::\n The command being run will still be logged at the ``debug``\n loglevel regardless, unless ``quiet`` is used for this value.\n\n hide_output : False\n Suppress stdout and stderr in the state's results.\n\n .. note::\n This is separate from ``output_loglevel``, which only handles how\n Salt logs to the minion log.\n\n .. versionadded:: 2018.3.0\n\n success_retcodes: This parameter will be allow a list of\n non-zero return codes that should be considered a success. If the\n return code returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: 2019.2.0\n\n success_stdout: This parameter will be allow a list of\n strings that when found in standard out should be considered a success.\n If stdout returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n success_stderr: This parameter will be allow a list of\n strings that when found in standard error should be considered a success.\n If stderr returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n '''\n test_name = None\n if not isinstance(stateful, list):\n stateful = stateful is True\n elif isinstance(stateful, list) and 'test_name' in stateful[0]:\n test_name = stateful[0]['test_name']\n if __opts__['test'] and test_name:\n name = test_name\n\n ret = {'name': name,\n 'changes': {},\n 'result': False,\n 'comment': ''}\n\n # Need the check for None here, if env is not provided then it falls back\n # to None and it is assumed that the environment is not being overridden.\n if env is not None and not isinstance(env, (list, dict)):\n ret['comment'] = ('Invalidly-formatted \\'env\\' parameter. See '\n 'documentation.')\n return ret\n\n if context and not isinstance(context, dict):\n ret['comment'] = ('Invalidly-formatted \\'context\\' parameter. Must '\n 'be formed as a dict.')\n return ret\n if defaults and not isinstance(defaults, dict):\n ret['comment'] = ('Invalidly-formatted \\'defaults\\' parameter. Must '\n 'be formed as a dict.')\n return ret\n\n tmpctx = defaults if defaults else {}\n if context:\n tmpctx.update(context)\n\n cmd_kwargs = copy.deepcopy(kwargs)\n cmd_kwargs.update({'runas': runas,\n 'shell': shell or __grains__['shell'],\n 'env': env,\n 'onlyif': onlyif,\n 'unless': unless,\n 'cwd': cwd,\n 'template': template,\n 'umask': umask,\n 'timeout': timeout,\n 'output_loglevel': output_loglevel,\n 'hide_output': hide_output,\n 'use_vt': use_vt,\n 'context': tmpctx,\n 'saltenv': __env__,\n 'success_retcodes': success_retcodes,\n 'success_stdout': success_stdout,\n 'success_stderr': success_stderr})\n\n run_check_cmd_kwargs = {\n 'cwd': cwd,\n 'runas': runas,\n 'shell': shell or __grains__['shell']\n }\n\n # Change the source to be the name arg if it is not specified\n if source is None:\n source = name\n\n # If script args present split from name and define args\n if not cmd_kwargs.get('args', None) and len(name.split()) > 1:\n cmd_kwargs.update({'args': name.split(' ', 1)[1]})\n\n cret = mod_run_check(\n run_check_cmd_kwargs, onlyif, unless, creates\n )\n if isinstance(cret, dict):\n ret.update(cret)\n return ret\n\n if __opts__['test'] and not test_name:\n ret['result'] = None\n ret['comment'] = 'Command \\'{0}\\' would have been ' \\\n 'executed'.format(name)\n return _reinterpreted_state(ret) if stateful else ret\n\n if cwd and not os.path.isdir(cwd):\n ret['comment'] = (\n 'Desired working directory \"{0}\" '\n 'is not available'\n ).format(cwd)\n return ret\n\n # Wow, we passed the test, run this sucker!\n try:\n cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)\n except (CommandExecutionError, SaltRenderError, IOError) as err:\n ret['comment'] = six.text_type(err)\n return ret\n\n ret['changes'] = cmd_all\n if kwargs.get('retcode', False):\n ret['result'] = not bool(cmd_all)\n else:\n ret['result'] = not bool(cmd_all['retcode'])\n if ret.get('changes', {}).get('cache_error'):\n ret['comment'] = 'Unable to cache script {0} from saltenv ' \\\n '\\'{1}\\''.format(source, __env__)\n else:\n ret['comment'] = 'Command \\'{0}\\' run'.format(name)\n if stateful:\n ret = _reinterpreted_state(ret)\n if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:\n ret['result'] = None\n return ret\n",
"def call(name,\n func,\n args=(),\n kws=None,\n onlyif=None,\n unless=None,\n creates=None,\n output_loglevel='debug',\n hide_output=False,\n use_vt=False,\n **kwargs):\n '''\n Invoke a pre-defined Python function with arguments specified in the state\n declaration. This function is mainly used by the\n :mod:`salt.renderers.pydsl` renderer.\n\n The interpretation of ``onlyif`` and ``unless`` arguments are identical to\n those of :mod:`cmd.run <salt.states.cmd.run>`, and all other\n arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run\n <salt.states.cmd.run>` are allowed here, except that their effects apply\n only to the commands specified in `onlyif` and `unless` rather than to the\n function to be invoked.\n\n In addition, the ``stateful`` argument has no effects here.\n\n The return value of the invoked function will be interpreted as follows.\n\n If it's a dictionary then it will be passed through to the state system,\n which expects it to have the usual structure returned by any salt state\n function.\n\n Otherwise, the return value (denoted as ``result`` in the code below) is\n expected to be a JSON serializable object, and this dictionary is returned:\n\n .. code-block:: python\n\n {\n 'name': name\n 'changes': {'retval': result},\n 'result': True if result is None else bool(result),\n 'comment': result if isinstance(result, six.string_types) else ''\n }\n '''\n ret = {'name': name,\n 'changes': {},\n 'result': False,\n 'comment': ''}\n\n cmd_kwargs = {'cwd': kwargs.get('cwd'),\n 'runas': kwargs.get('user'),\n 'shell': kwargs.get('shell') or __grains__['shell'],\n 'env': kwargs.get('env'),\n 'use_vt': use_vt,\n 'output_loglevel': output_loglevel,\n 'hide_output': hide_output,\n 'umask': kwargs.get('umask')}\n\n cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)\n if isinstance(cret, dict):\n ret.update(cret)\n return ret\n\n if not kws:\n kws = {}\n result = func(*args, **kws)\n if isinstance(result, dict):\n ret.update(result)\n return ret\n else:\n # result must be JSON serializable else we get an error\n ret['changes'] = {'retval': result}\n ret['result'] = True if result is None else bool(result)\n if isinstance(result, six.string_types):\n ret['comment'] = result\n return ret\n",
"def run(name,\n onlyif=None,\n unless=None,\n creates=None,\n cwd=None,\n root=None,\n runas=None,\n shell=None,\n env=None,\n prepend_path=None,\n stateful=False,\n umask=None,\n output_loglevel='debug',\n hide_output=False,\n timeout=None,\n ignore_timeout=False,\n use_vt=False,\n success_retcodes=None,\n success_stdout=None,\n success_stderr=None,\n **kwargs):\n '''\n Run a command if certain circumstances are met. Use ``cmd.wait`` if you\n want to use the ``watch`` requisite.\n\n name\n The command to execute, remember that the command will execute with the\n path and permissions of the salt-minion.\n\n onlyif\n A command to run as a check, run the named command only if the command\n passed to the ``onlyif`` option returns a zero exit status\n\n unless\n A command to run as a check, only run the named command if the command\n passed to the ``unless`` option returns a non-zero exit status\n\n cwd\n The current working directory to execute the command in, defaults to\n /root\n\n root\n Path to the root of the jail to use. If this parameter is set, the command\n will run inside a chroot\n\n runas\n The user name to run the command as\n\n shell\n The shell to use for execution, defaults to the shell grain\n\n env\n A list of environment variables to be set prior to execution.\n Example:\n\n .. code-block:: yaml\n\n script-foo:\n cmd.run:\n - env:\n - BATCH: 'yes'\n\n .. warning::\n\n The above illustrates a common PyYAML pitfall, that **yes**,\n **no**, **on**, **off**, **true**, and **false** are all loaded as\n boolean ``True`` and ``False`` values, and must be enclosed in\n quotes to be used as strings. More info on this (and other) PyYAML\n idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.\n\n Variables as values are not evaluated. So $PATH in the following\n example is a literal '$PATH':\n\n .. code-block:: yaml\n\n script-bar:\n cmd.run:\n - env: \"PATH=/some/path:$PATH\"\n\n One can still use the existing $PATH by using a bit of Jinja:\n\n .. code-block:: jinja\n\n {% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}\n\n mycommand:\n cmd.run:\n - name: ls -l /\n - env:\n - PATH: {{ [current_path, '/my/special/bin']|join(':') }}\n\n prepend_path\n $PATH segment to prepend (trailing ':' not necessary) to $PATH. This is\n an easier alternative to the Jinja workaround.\n\n .. versionadded:: 2018.3.0\n\n stateful\n The command being executed is expected to return data about executing\n a state. For more information, see the :ref:`stateful-argument` section.\n\n umask\n The umask (in octal) to use when running the command.\n\n output_loglevel : debug\n Control the loglevel at which the output from the command is logged to\n the minion log.\n\n .. note::\n The command being run will still be logged at the ``debug``\n loglevel regardless, unless ``quiet`` is used for this value.\n\n hide_output : False\n Suppress stdout and stderr in the state's results.\n\n .. note::\n This is separate from ``output_loglevel``, which only handles how\n Salt logs to the minion log.\n\n .. versionadded:: 2018.3.0\n\n quiet\n This option no longer has any functionality and will be removed, please\n set ``output_loglevel`` to ``quiet`` to suppress logging of the\n command.\n\n .. deprecated:: 2014.1.0\n\n timeout\n If the command has not terminated after timeout seconds, send the\n subprocess sigterm, and if sigterm is ignored, follow up with sigkill\n\n ignore_timeout\n Ignore the timeout of commands, which is useful for running nohup\n processes.\n\n .. versionadded:: 2015.8.0\n\n creates\n Only run if the file specified by ``creates`` do not exist. If you\n specify a list of files then this state will only run if **any** of\n the files does not exist.\n\n .. versionadded:: 2014.7.0\n\n use_vt : False\n Use VT utils (saltstack) to stream the command output more\n interactively to the console and the logs.\n This is experimental.\n\n bg : False\n If ``True``, run command in background and do not await or deliver its\n results.\n\n .. versionadded:: 2016.3.6\n\n success_retcodes: This parameter will be allow a list of\n non-zero return codes that should be considered a success. If the\n return code returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: 2019.2.0\n\n success_stdout: This parameter will be allow a list of\n strings that when found in standard out should be considered a success.\n If stdout returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n success_stderr: This parameter will be allow a list of\n strings that when found in standard error should be considered a success.\n If stderr returned from the run matches any in the provided list,\n the return code will be overridden with zero.\n\n .. versionadded:: Neon\n\n .. note::\n\n cmd.run supports the usage of ``reload_modules``. This functionality\n allows you to force Salt to reload all modules. You should only use\n ``reload_modules`` if your cmd.run does some sort of installation\n (such as ``pip``), if you do not reload the modules future items in\n your state which rely on the software being installed will fail.\n\n .. code-block:: yaml\n\n getpip:\n cmd.run:\n - name: /usr/bin/python /usr/local/sbin/get-pip.py\n - unless: which pip\n - require:\n - pkg: python\n - file: /usr/local/sbin/get-pip.py\n - reload_modules: True\n\n '''\n ### NOTE: The keyword arguments in **kwargs are passed directly to the\n ### ``cmd.run_all`` function and cannot be removed from the function\n ### definition, otherwise the use of unsupported arguments in a\n ### ``cmd.run`` state will result in a traceback.\n\n ret = {'name': name,\n 'changes': {},\n 'result': False,\n 'comment': ''}\n\n if 'quiet' in kwargs:\n quiet = kwargs.pop('quiet')\n msg = (\n 'The \\'quiet\\' argument for cmd.run has been deprecated since '\n '2014.1.0 and will be removed as of the Neon release. Please set '\n '\\'output_loglevel\\' to \\'quiet\\' instead.'\n )\n salt.utils.versions.warn_until('Neon', msg)\n ret.setdefault('warnings', []).append(msg)\n else:\n quiet = False\n\n test_name = None\n if not isinstance(stateful, list):\n stateful = stateful is True\n elif isinstance(stateful, list) and 'test_name' in stateful[0]:\n test_name = stateful[0]['test_name']\n if __opts__['test'] and test_name:\n name = test_name\n\n # Need the check for None here, if env is not provided then it falls back\n # to None and it is assumed that the environment is not being overridden.\n if env is not None and not isinstance(env, (list, dict)):\n ret['comment'] = ('Invalidly-formatted \\'env\\' parameter. See '\n 'documentation.')\n return ret\n\n cmd_kwargs = copy.deepcopy(kwargs)\n cmd_kwargs.update({'cwd': cwd,\n 'root': root,\n 'runas': runas,\n 'use_vt': use_vt,\n 'shell': shell or __grains__['shell'],\n 'env': env,\n 'prepend_path': prepend_path,\n 'umask': umask,\n 'output_loglevel': output_loglevel,\n 'hide_output': hide_output,\n 'quiet': quiet,\n 'success_retcodes': success_retcodes,\n 'success_stdout': success_stdout,\n 'success_stderr': success_stderr})\n\n cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)\n if isinstance(cret, dict):\n ret.update(cret)\n return ret\n\n if __opts__['test'] and not test_name:\n ret['result'] = None\n ret['comment'] = 'Command \"{0}\" would have been executed'.format(name)\n return _reinterpreted_state(ret) if stateful else ret\n\n if cwd and not os.path.isdir(cwd):\n ret['comment'] = (\n 'Desired working directory \"{0}\" '\n 'is not available'\n ).format(cwd)\n return ret\n\n # Wow, we passed the test, run this sucker!\n try:\n run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'\n cmd_all = __salt__[run_cmd](\n cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs\n )\n except Exception as err:\n ret['comment'] = six.text_type(err)\n return ret\n\n ret['changes'] = cmd_all\n ret['result'] = not bool(cmd_all['retcode'])\n ret['comment'] = 'Command \"{0}\" run'.format(name)\n\n # Ignore timeout errors if asked (for nohups) and treat cmd as a success\n if ignore_timeout:\n trigger = 'Timed out after'\n if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):\n ret['changes']['retcode'] = 0\n ret['result'] = True\n\n if stateful:\n ret = _reinterpreted_state(ret)\n if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:\n ret['result'] = None\n return ret\n",
"def _reinterpreted_state(state):\n '''\n Re-interpret the state returned by salt.state.run using our protocol.\n '''\n ret = state['changes']\n state['changes'] = {}\n state['comment'] = ''\n\n out = ret.get('stdout')\n if not out:\n if ret.get('stderr'):\n state['comment'] = ret['stderr']\n return state\n\n is_json = False\n try:\n data = salt.utils.json.loads(out)\n if not isinstance(data, dict):\n return _failout(\n state,\n 'script JSON output must be a JSON object (e.g., {})!'\n )\n is_json = True\n except ValueError:\n idx = out.rstrip().rfind('\\n')\n if idx != -1:\n out = out[idx + 1:]\n data = {}\n try:\n for item in salt.utils.args.shlex_split(out):\n key, val = item.split('=')\n data[key] = val\n except ValueError:\n state = _failout(\n state,\n 'Failed parsing script output! '\n 'Stdout must be JSON or a line of name=value pairs.'\n )\n state['changes'].update(ret)\n return state\n\n changed = _is_true(data.get('changed', 'no'))\n\n if 'comment' in data:\n state['comment'] = data['comment']\n del data['comment']\n\n if changed:\n for key in ret:\n data.setdefault(key, ret[key])\n\n # if stdout is the state output in JSON, don't show it.\n # otherwise it contains the one line name=value pairs, strip it.\n data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]\n state['changes'] = data\n\n #FIXME: if it's not changed but there's stdout and/or stderr then those\n # won't be shown as the function output. (though, they will be shown\n # inside INFO logs).\n return state\n"
] |
# -*- coding: utf-8 -*-
'''
Execution of arbitrary commands
===============================
The cmd state module manages the enforcement of executed commands, this
state can tell a command to run under certain circumstances.
A simple example to execute a command:
.. code-block:: yaml
# Store the current date in a file
'date > /tmp/salt-run':
cmd.run
Only run if another execution failed, in this case truncate syslog if there is
no disk space:
.. code-block:: yaml
'> /var/log/messages/:
cmd.run:
- unless: echo 'foo' > /tmp/.test && rm -f /tmp/.test
Only run if the file specified by ``creates`` does not exist, in this case
touch /tmp/foo if it does not exist:
.. code-block:: yaml
touch /tmp/foo:
cmd.run:
- creates: /tmp/foo
``creates`` also accepts a list of files, in which case this state will
run if **any** of the files does not exist:
.. code-block:: yaml
"echo 'foo' | tee /tmp/bar > /tmp/baz":
cmd.run:
- creates:
- /tmp/bar
- /tmp/baz
.. note::
The ``creates`` option was added to version 2014.7.0
Sometimes when running a command that starts up a daemon, the init script
doesn't return properly which causes Salt to wait indefinitely for a response.
In situations like this try the following:
.. code-block:: yaml
run_installer:
cmd.run:
- name: /tmp/installer.bin > /dev/null 2>&1
Salt determines whether the ``cmd`` state is successfully enforced based on the exit
code returned by the command. If the command returns a zero exit code, then salt
determines that the state was successfully enforced. If the script returns a non-zero
exit code, then salt determines that it failed to successfully enforce the state.
If a command returns a non-zero exit code but you wish to treat this as a success,
then you must place the command in a script and explicitly set the exit code of
the script to zero.
Please note that the success or failure of the state is not affected by whether a state
change occurred nor the stateful argument.
When executing a command or script, the state (i.e., changed or not)
of the command is unknown to Salt's state system. Therefore, by default, the
``cmd`` state assumes that any command execution results in a changed state.
This means that if a ``cmd`` state is watched by another state then the
state that's watching will always be executed due to the `changed` state in
the ``cmd`` state.
.. _stateful-argument:
Using the "Stateful" Argument
-----------------------------
Many state functions in this module now also accept a ``stateful`` argument.
If ``stateful`` is specified to be true then it is assumed that the command
or script will determine its own state and communicate it back by following
a simple protocol described below:
1. :strong:`If there's nothing in the stdout of the command, then assume no
changes.` Otherwise, the stdout must be either in JSON or its `last`
non-empty line must be a string of key=value pairs delimited by spaces (no
spaces on either side of ``=``).
2. :strong:`If it's JSON then it must be a JSON object (e.g., {}).` If it's
key=value pairs then quoting may be used to include spaces. (Python's shlex
module is used to parse the key=value string)
Two special keys or attributes are recognized in the output::
changed: bool (i.e., 'yes', 'no', 'true', 'false', case-insensitive)
comment: str (i.e., any string)
So, only if ``changed`` is ``True`` then assume the command execution has
changed the state, and any other key values or attributes in the output will
be set as part of the changes.
3. :strong:`If there's a comment then it will be used as the comment of the
state.`
Here's an example of how one might write a shell script for use with a
stateful command:
.. code-block:: bash
#!/bin/bash
#
echo "Working hard..."
# writing the state line
echo # an empty line here so the next line will be the last.
echo "changed=yes comment='something has changed' whatever=123"
And an example SLS file using this module:
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful: True
Run only if myscript changed something:
cmd.run:
- name: echo hello
- cwd: /
- onchanges:
- cmd: Run myscript
Note that if the second ``cmd.run`` state also specifies ``stateful: True`` it can
then be watched by some other states as well.
4. :strong:`The stateful argument can optionally include a test_name parameter.`
This is used to specify a command to run in test mode. This command should
return stateful data for changes that would be made by the command in the
name parameter.
.. versionadded:: 2015.2.0
.. code-block:: yaml
Run myscript:
cmd.run:
- name: /path/to/myscript
- cwd: /
- stateful:
- test_name: /path/to/myscript test
Run masterscript:
cmd.script:
- name: masterscript
- source: salt://path/to/masterscript
- cwd: /
- stateful:
- test_name: masterscript test
Should I use :mod:`cmd.run <salt.states.cmd.run>` or :mod:`cmd.wait <salt.states.cmd.wait>`?
--------------------------------------------------------------------------------------------
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :ref:`onchanges <requisites-onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
These two states are often confused. The important thing to remember about them
is that :mod:`cmd.run <salt.states.cmd.run>` states are run each time the SLS
file that contains them is applied. If it is more desirable to have a command
that only runs after some other state changes, then :mod:`cmd.wait
<salt.states.cmd.wait>` does just that. :mod:`cmd.wait <salt.states.cmd.wait>`
is designed to :ref:`watch <requisites-watch>` other states, and is
executed when the state it is watching changes. Example:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.wait:
- watch:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
``cmd.wait`` itself does not do anything; all functionality is inside its ``mod_watch``
function, which is called by ``watch`` on changes.
The preferred format is using the :ref:`onchanges Requisite <requisites-onchanges>`, which
works on ``cmd.run`` as well as on any other state. The example would then look as follows:
.. code-block:: yaml
/usr/local/bin/postinstall.sh:
cmd.run:
- onchanges:
- pkg: mycustompkg
file.managed:
- source: salt://utils/scripts/postinstall.sh
mycustompkg:
pkg.installed:
- require:
- file: /usr/local/bin/postinstall.sh
How do I create an environment from a pillar map?
-------------------------------------------------
The map that comes from a pillar can be directly consumed by the env option!
To use it, one may pass it like this. Example:
.. code-block:: yaml
printenv:
cmd.run:
- env: {{ salt['pillar.get']('example:key', {}) }}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import copy
import logging
# Import salt libs
import salt.utils.args
import salt.utils.functools
import salt.utils.json
from salt.exceptions import CommandExecutionError, SaltRenderError
from salt.ext import six
log = logging.getLogger(__name__)
def _reinterpreted_state(state):
'''
Re-interpret the state returned by salt.state.run using our protocol.
'''
ret = state['changes']
state['changes'] = {}
state['comment'] = ''
out = ret.get('stdout')
if not out:
if ret.get('stderr'):
state['comment'] = ret['stderr']
return state
is_json = False
try:
data = salt.utils.json.loads(out)
if not isinstance(data, dict):
return _failout(
state,
'script JSON output must be a JSON object (e.g., {})!'
)
is_json = True
except ValueError:
idx = out.rstrip().rfind('\n')
if idx != -1:
out = out[idx + 1:]
data = {}
try:
for item in salt.utils.args.shlex_split(out):
key, val = item.split('=')
data[key] = val
except ValueError:
state = _failout(
state,
'Failed parsing script output! '
'Stdout must be JSON or a line of name=value pairs.'
)
state['changes'].update(ret)
return state
changed = _is_true(data.get('changed', 'no'))
if 'comment' in data:
state['comment'] = data['comment']
del data['comment']
if changed:
for key in ret:
data.setdefault(key, ret[key])
# if stdout is the state output in JSON, don't show it.
# otherwise it contains the one line name=value pairs, strip it.
data['stdout'] = '' if is_json else data.get('stdout', '')[:idx]
state['changes'] = data
#FIXME: if it's not changed but there's stdout and/or stderr then those
# won't be shown as the function output. (though, they will be shown
# inside INFO logs).
return state
def _failout(state, msg):
state['comment'] = msg
state['result'] = False
return state
def _is_true(val):
if val and six.text_type(val).lower() in ('true', 'yes', '1'):
return True
elif six.text_type(val).lower() in ('false', 'no', '0'):
return False
raise ValueError('Failed parsing boolean value: {0}'.format(val))
def mod_run_check(cmd_kwargs, onlyif, unless, creates):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
# never use VT for onlyif/unless executions because this will lead
# to quote problems
cmd_kwargs = copy.deepcopy(cmd_kwargs)
cmd_kwargs['use_vt'] = False
cmd_kwargs['bg'] = False
if onlyif is not None:
if isinstance(onlyif, six.string_types):
cmd = __salt__['cmd.retcode'](onlyif, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
elif isinstance(onlyif, list):
for entry in onlyif:
cmd = __salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command \'%s\' return code: %s', entry, cmd)
if cmd != 0:
return {'comment': 'onlyif condition is false: {0}'.format(entry),
'skip_watch': True,
'result': True}
elif not isinstance(onlyif, six.string_types):
if not onlyif:
log.debug('Command not run: onlyif did not evaluate to string_type')
return {'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True}
if unless is not None:
if isinstance(unless, six.string_types):
cmd = __salt__['cmd.retcode'](unless, ignore_retcode=True, python_shell=True, **cmd_kwargs)
log.debug('Last command return code: %s', cmd)
if cmd == 0:
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif isinstance(unless, list):
cmd = []
for entry in unless:
cmd.append(__salt__['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_kwargs))
log.debug('Last command return code: %s', cmd)
if all([c == 0 for c in cmd]):
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
elif not isinstance(unless, six.string_types):
if unless:
log.debug('Command not run: unless did not evaluate to string_type')
return {'comment': 'unless condition is true',
'skip_watch': True,
'result': True}
if isinstance(creates, six.string_types) and os.path.exists(creates):
return {'comment': '{0} exists'.format(creates),
'result': True}
elif isinstance(creates, list) and all([
os.path.exists(path) for path in creates
]):
return {'comment': 'All files in creates exist',
'result': True}
# No reason to stop, return True
return True
def wait(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=(),
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run the given command only if the watch statement calls it.
.. note::
Use :mod:`cmd.run <salt.states.cmd.run>` together with :mod:`onchanges </ref/states/requisites#onchanges>`
instead of :mod:`cmd.wait <salt.states.cmd.wait>`.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to /bin/sh
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.wait:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.wait:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
# Alias "cmd.watch" to "cmd.wait", as this is a common misconfiguration
watch = salt.utils.functools.alias_function(wait, 'watch')
def wait_script(name,
source=None,
template=None,
onlyif=None,
unless=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script from a remote source and execute it only if a watch
statement calls it.
source
The source script being downloaded to the minion, this source script is
hosted on the salt master server. If the file is located on the master
in the directory named spam, and is called eggs, the source string is
salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file, currently jinja, mako, and wempy
are supported
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns true
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.wait_script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.wait_script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
def run(name,
onlyif=None,
unless=None,
creates=None,
cwd=None,
root=None,
runas=None,
shell=None,
env=None,
prepend_path=None,
stateful=False,
umask=None,
output_loglevel='debug',
hide_output=False,
timeout=None,
ignore_timeout=False,
use_vt=False,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Run a command if certain circumstances are met. Use ``cmd.wait`` if you
want to use the ``watch`` requisite.
name
The command to execute, remember that the command will execute with the
path and permissions of the salt-minion.
onlyif
A command to run as a check, run the named command only if the command
passed to the ``onlyif`` option returns a zero exit status
unless
A command to run as a check, only run the named command if the command
passed to the ``unless`` option returns a non-zero exit status
cwd
The current working directory to execute the command in, defaults to
/root
root
Path to the root of the jail to use. If this parameter is set, the command
will run inside a chroot
runas
The user name to run the command as
shell
The shell to use for execution, defaults to the shell grain
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
script-foo:
cmd.run:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
script-bar:
cmd.run:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
prepend_path
$PATH segment to prepend (trailing ':' not necessary) to $PATH. This is
an easier alternative to the Jinja workaround.
.. versionadded:: 2018.3.0
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
umask
The umask (in octal) to use when running the command.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
quiet
This option no longer has any functionality and will be removed, please
set ``output_loglevel`` to ``quiet`` to suppress logging of the
command.
.. deprecated:: 2014.1.0
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
ignore_timeout
Ignore the timeout of commands, which is useful for running nohup
processes.
.. versionadded:: 2015.8.0
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt : False
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
bg : False
If ``True``, run command in background and do not await or deliver its
results.
.. versionadded:: 2016.3.6
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
.. note::
cmd.run supports the usage of ``reload_modules``. This functionality
allows you to force Salt to reload all modules. You should only use
``reload_modules`` if your cmd.run does some sort of installation
(such as ``pip``), if you do not reload the modules future items in
your state which rely on the software being installed will fail.
.. code-block:: yaml
getpip:
cmd.run:
- name: /usr/bin/python /usr/local/sbin/get-pip.py
- unless: which pip
- require:
- pkg: python
- file: /usr/local/sbin/get-pip.py
- reload_modules: True
'''
### NOTE: The keyword arguments in **kwargs are passed directly to the
### ``cmd.run_all`` function and cannot be removed from the function
### definition, otherwise the use of unsupported arguments in a
### ``cmd.run`` state will result in a traceback.
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if 'quiet' in kwargs:
quiet = kwargs.pop('quiet')
msg = (
'The \'quiet\' argument for cmd.run has been deprecated since '
'2014.1.0 and will be removed as of the Neon release. Please set '
'\'output_loglevel\' to \'quiet\' instead.'
)
salt.utils.versions.warn_until('Neon', msg)
ret.setdefault('warnings', []).append(msg)
else:
quiet = False
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'cwd': cwd,
'root': root,
'runas': runas,
'use_vt': use_vt,
'shell': shell or __grains__['shell'],
'env': env,
'prepend_path': prepend_path,
'umask': umask,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'quiet': quiet,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command "{0}" would have been executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
run_cmd = 'cmd.run_all' if not root else 'cmd.run_chroot'
cmd_all = __salt__[run_cmd](
cmd=name, timeout=timeout, python_shell=True, **cmd_kwargs
)
except Exception as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
ret['result'] = not bool(cmd_all['retcode'])
ret['comment'] = 'Command "{0}" run'.format(name)
# Ignore timeout errors if asked (for nohups) and treat cmd as a success
if ignore_timeout:
trigger = 'Timed out after'
if ret['changes'].get('retcode') == 1 and trigger in ret['changes'].get('stdout'):
ret['changes']['retcode'] = 0
ret['result'] = True
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def script(name,
source=None,
template=None,
onlyif=None,
unless=None,
creates=None,
cwd=None,
runas=None,
shell=None,
env=None,
stateful=False,
umask=None,
timeout=None,
use_vt=False,
output_loglevel='debug',
hide_output=False,
defaults=None,
context=None,
success_retcodes=None,
success_stdout=None,
success_stderr=None,
**kwargs):
'''
Download a script and execute it with specified arguments.
source
The location of the script to download. If the file is located on the
master in the directory named spam, and is called eggs, the source
string is salt://spam/eggs
template
If this setting is applied then the named templating engine will be
used to render the downloaded file. Currently jinja, mako, and wempy
are supported
name
Either "cmd arg1 arg2 arg3..." (cmd is not used) or a source
"salt://...".
onlyif
Run the named command only if the command passed to the ``onlyif``
option returns true
unless
Run the named command only if the command passed to the ``unless``
option returns false
cwd
The current working directory to execute the command in, defaults to
/root
runas
The name of the user to run the command as
shell
The shell to use for execution. The default is set in grains['shell']
env
A list of environment variables to be set prior to execution.
Example:
.. code-block:: yaml
salt://scripts/foo.sh:
cmd.script:
- env:
- BATCH: 'yes'
.. warning::
The above illustrates a common PyYAML pitfall, that **yes**,
**no**, **on**, **off**, **true**, and **false** are all loaded as
boolean ``True`` and ``False`` values, and must be enclosed in
quotes to be used as strings. More info on this (and other) PyYAML
idiosyncrasies can be found :ref:`here <yaml-idiosyncrasies>`.
Variables as values are not evaluated. So $PATH in the following
example is a literal '$PATH':
.. code-block:: yaml
salt://scripts/bar.sh:
cmd.script:
- env: "PATH=/some/path:$PATH"
One can still use the existing $PATH by using a bit of Jinja:
.. code-block:: jinja
{% set current_path = salt['environ.get']('PATH', '/bin:/usr/bin') %}
mycommand:
cmd.run:
- name: ls -l /
- env:
- PATH: {{ [current_path, '/my/special/bin']|join(':') }}
saltenv : ``base``
The Salt environment to use
umask
The umask (in octal) to use when running the command.
stateful
The command being executed is expected to return data about executing
a state. For more information, see the :ref:`stateful-argument` section.
timeout
If the command has not terminated after timeout seconds, send the
subprocess sigterm, and if sigterm is ignored, follow up with sigkill
args
String of command line args to pass to the script. Only used if no
args are specified as part of the `name` argument. To pass a string
containing spaces in YAML, you will need to doubly-quote it: "arg1
'arg two' arg3"
creates
Only run if the file specified by ``creates`` do not exist. If you
specify a list of files then this state will only run if **any** of
the files does not exist.
.. versionadded:: 2014.7.0
use_vt
Use VT utils (saltstack) to stream the command output more
interactively to the console and the logs.
This is experimental.
context
.. versionadded:: 2016.3.0
Overrides default context variables passed to the template.
defaults
.. versionadded:: 2016.3.0
Default context passed to the template.
output_loglevel : debug
Control the loglevel at which the output from the command is logged to
the minion log.
.. note::
The command being run will still be logged at the ``debug``
loglevel regardless, unless ``quiet`` is used for this value.
hide_output : False
Suppress stdout and stderr in the state's results.
.. note::
This is separate from ``output_loglevel``, which only handles how
Salt logs to the minion log.
.. versionadded:: 2018.3.0
success_retcodes: This parameter will be allow a list of
non-zero return codes that should be considered a success. If the
return code returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: 2019.2.0
success_stdout: This parameter will be allow a list of
strings that when found in standard out should be considered a success.
If stdout returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
success_stderr: This parameter will be allow a list of
strings that when found in standard error should be considered a success.
If stderr returned from the run matches any in the provided list,
the return code will be overridden with zero.
.. versionadded:: Neon
'''
test_name = None
if not isinstance(stateful, list):
stateful = stateful is True
elif isinstance(stateful, list) and 'test_name' in stateful[0]:
test_name = stateful[0]['test_name']
if __opts__['test'] and test_name:
name = test_name
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
# Need the check for None here, if env is not provided then it falls back
# to None and it is assumed that the environment is not being overridden.
if env is not None and not isinstance(env, (list, dict)):
ret['comment'] = ('Invalidly-formatted \'env\' parameter. See '
'documentation.')
return ret
if context and not isinstance(context, dict):
ret['comment'] = ('Invalidly-formatted \'context\' parameter. Must '
'be formed as a dict.')
return ret
if defaults and not isinstance(defaults, dict):
ret['comment'] = ('Invalidly-formatted \'defaults\' parameter. Must '
'be formed as a dict.')
return ret
tmpctx = defaults if defaults else {}
if context:
tmpctx.update(context)
cmd_kwargs = copy.deepcopy(kwargs)
cmd_kwargs.update({'runas': runas,
'shell': shell or __grains__['shell'],
'env': env,
'onlyif': onlyif,
'unless': unless,
'cwd': cwd,
'template': template,
'umask': umask,
'timeout': timeout,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'use_vt': use_vt,
'context': tmpctx,
'saltenv': __env__,
'success_retcodes': success_retcodes,
'success_stdout': success_stdout,
'success_stderr': success_stderr})
run_check_cmd_kwargs = {
'cwd': cwd,
'runas': runas,
'shell': shell or __grains__['shell']
}
# Change the source to be the name arg if it is not specified
if source is None:
source = name
# If script args present split from name and define args
if not cmd_kwargs.get('args', None) and len(name.split()) > 1:
cmd_kwargs.update({'args': name.split(' ', 1)[1]})
cret = mod_run_check(
run_check_cmd_kwargs, onlyif, unless, creates
)
if isinstance(cret, dict):
ret.update(cret)
return ret
if __opts__['test'] and not test_name:
ret['result'] = None
ret['comment'] = 'Command \'{0}\' would have been ' \
'executed'.format(name)
return _reinterpreted_state(ret) if stateful else ret
if cwd and not os.path.isdir(cwd):
ret['comment'] = (
'Desired working directory "{0}" '
'is not available'
).format(cwd)
return ret
# Wow, we passed the test, run this sucker!
try:
cmd_all = __salt__['cmd.script'](source, python_shell=True, **cmd_kwargs)
except (CommandExecutionError, SaltRenderError, IOError) as err:
ret['comment'] = six.text_type(err)
return ret
ret['changes'] = cmd_all
if kwargs.get('retcode', False):
ret['result'] = not bool(cmd_all)
else:
ret['result'] = not bool(cmd_all['retcode'])
if ret.get('changes', {}).get('cache_error'):
ret['comment'] = 'Unable to cache script {0} from saltenv ' \
'\'{1}\''.format(source, __env__)
else:
ret['comment'] = 'Command \'{0}\' run'.format(name)
if stateful:
ret = _reinterpreted_state(ret)
if __opts__['test'] and cmd_all['retcode'] == 0 and ret['changes']:
ret['result'] = None
return ret
def call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
output_loglevel='debug',
hide_output=False,
use_vt=False,
**kwargs):
'''
Invoke a pre-defined Python function with arguments specified in the state
declaration. This function is mainly used by the
:mod:`salt.renderers.pydsl` renderer.
The interpretation of ``onlyif`` and ``unless`` arguments are identical to
those of :mod:`cmd.run <salt.states.cmd.run>`, and all other
arguments(``cwd``, ``runas``, ...) allowed by :mod:`cmd.run
<salt.states.cmd.run>` are allowed here, except that their effects apply
only to the commands specified in `onlyif` and `unless` rather than to the
function to be invoked.
In addition, the ``stateful`` argument has no effects here.
The return value of the invoked function will be interpreted as follows.
If it's a dictionary then it will be passed through to the state system,
which expects it to have the usual structure returned by any salt state
function.
Otherwise, the return value (denoted as ``result`` in the code below) is
expected to be a JSON serializable object, and this dictionary is returned:
.. code-block:: python
{
'name': name
'changes': {'retval': result},
'result': True if result is None else bool(result),
'comment': result if isinstance(result, six.string_types) else ''
}
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
cmd_kwargs = {'cwd': kwargs.get('cwd'),
'runas': kwargs.get('user'),
'shell': kwargs.get('shell') or __grains__['shell'],
'env': kwargs.get('env'),
'use_vt': use_vt,
'output_loglevel': output_loglevel,
'hide_output': hide_output,
'umask': kwargs.get('umask')}
cret = mod_run_check(cmd_kwargs, onlyif, unless, creates)
if isinstance(cret, dict):
ret.update(cret)
return ret
if not kws:
kws = {}
result = func(*args, **kws)
if isinstance(result, dict):
ret.update(result)
return ret
else:
# result must be JSON serializable else we get an error
ret['changes'] = {'retval': result}
ret['result'] = True if result is None else bool(result)
if isinstance(result, six.string_types):
ret['comment'] = result
return ret
def wait_call(name,
func,
args=(),
kws=None,
onlyif=None,
unless=None,
creates=None,
stateful=False,
use_vt=False,
output_loglevel='debug',
hide_output=False,
**kwargs):
# Ignoring our arguments is intentional.
return {'name': name,
'changes': {},
'result': True,
'comment': ''}
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
check_nova
|
python
|
def check_nova():
'''
Check version of novaclient
'''
if HAS_NOVA:
novaclient_ver = _LooseVersion(novaclient.__version__)
min_ver = _LooseVersion(NOVACLIENT_MINVER)
if min_ver <= novaclient_ver:
return HAS_NOVA
log.debug('Newer novaclient version required. Minimum: %s', NOVACLIENT_MINVER)
return False
|
Check version of novaclient
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L67-L77
| null |
# -*- coding: utf-8 -*-
'''
Nova class
'''
# Import Python libs
from __future__ import absolute_import, with_statement, unicode_literals, print_function
import inspect
import logging
import time
import re
import json
# Import third party libs
from salt.ext import six
HAS_NOVA = False
# pylint: disable=import-error
try:
import novaclient
from novaclient import client
from novaclient.shell import OpenStackComputeShell
import novaclient.utils
import novaclient.exceptions
import novaclient.extension
import novaclient.base
HAS_NOVA = True
except ImportError:
pass
HAS_KEYSTONEAUTH = False
try:
import keystoneauth1.loading
import keystoneauth1.session
HAS_KEYSTONEAUTH = True
except ImportError:
pass
# pylint: enable=import-error
# Import salt libs
import salt.utils.cloud
import salt.utils.files
from salt.exceptions import SaltCloudSystemExit
from salt.utils.versions import LooseVersion as _LooseVersion
# Get logging started
log = logging.getLogger(__name__)
# Version added to novaclient.client.Client function
NOVACLIENT_MINVER = '2.6.1'
NOVACLIENT_MAXVER = '6.0.1'
# dict for block_device_mapping_v2
CLIENT_BDM2_KEYS = {
'id': 'uuid',
'source': 'source_type',
'dest': 'destination_type',
'bus': 'disk_bus',
'device': 'device_name',
'size': 'volume_size',
'format': 'guest_format',
'bootindex': 'boot_index',
'type': 'device_type',
'shutdown': 'delete_on_termination',
}
if check_nova():
try:
import novaclient.auth_plugin
except ImportError:
log.debug('Using novaclient version 7.0.0 or newer. Authentication '
'plugin auth_plugin.py is not available anymore.')
# kwargs has to be an object instead of a dictionary for the __post_parse_arg__
class KwargsStruct(object):
def __init__(self, **entries):
self.__dict__.update(entries)
def _parse_block_device_mapping_v2(block_device=None, boot_volume=None, snapshot=None, ephemeral=None, swap=None):
bdm = []
if block_device is None:
block_device = []
if ephemeral is None:
ephemeral = []
if boot_volume is not None:
bdm_dict = {'uuid': boot_volume, 'source_type': 'volume',
'destination_type': 'volume', 'boot_index': 0,
'delete_on_termination': False}
bdm.append(bdm_dict)
if snapshot is not None:
bdm_dict = {'uuid': snapshot, 'source_type': 'snapshot',
'destination_type': 'volume', 'boot_index': 0,
'delete_on_termination': False}
bdm.append(bdm_dict)
for device_spec in block_device:
bdm_dict = {}
for key, value in six.iteritems(device_spec):
bdm_dict[CLIENT_BDM2_KEYS[key]] = value
# Convert the delete_on_termination to a boolean or set it to true by
# default for local block devices when not specified.
if 'delete_on_termination' in bdm_dict:
action = bdm_dict['delete_on_termination']
bdm_dict['delete_on_termination'] = (action == 'remove')
elif bdm_dict.get('destination_type') == 'local':
bdm_dict['delete_on_termination'] = True
bdm.append(bdm_dict)
for ephemeral_spec in ephemeral:
bdm_dict = {'source_type': 'blank', 'destination_type': 'local',
'boot_index': -1, 'delete_on_termination': True}
if 'size' in ephemeral_spec:
bdm_dict['volume_size'] = ephemeral_spec['size']
if 'format' in ephemeral_spec:
bdm_dict['guest_format'] = ephemeral_spec['format']
bdm.append(bdm_dict)
if swap is not None:
bdm_dict = {'source_type': 'blank', 'destination_type': 'local',
'boot_index': -1, 'delete_on_termination': True,
'guest_format': 'swap', 'volume_size': swap}
bdm.append(bdm_dict)
return bdm
class NovaServer(object):
def __init__(self, name, server, password=None):
'''
Make output look like libcloud output for consistency
'''
self.name = name
self.id = server['id']
self.image = server.get('image', {}).get('id', 'Boot From Volume')
self.size = server['flavor']['id']
self.state = server['state']
self._uuid = None
self.extra = {
'metadata': server['metadata'],
'access_ip': server['accessIPv4']
}
self.addresses = server.get('addresses', {})
self.public_ips, self.private_ips = [], []
self.fixed_ips, self.floating_ips = [], []
for network in self.addresses.values():
for addr in network:
if salt.utils.cloud.is_public_ip(addr['addr']):
self.public_ips.append(addr['addr'])
else:
self.private_ips.append(addr['addr'])
if addr.get('OS-EXT-IPS:type') == 'floating':
self.floating_ips.append(addr['addr'])
else:
self.fixed_ips.append(addr['addr'])
if password:
self.extra['password'] = password
def __str__(self):
return self.__dict__
def get_entry(dict_, key, value, raise_error=True):
for entry in dict_:
if entry[key] == value:
return entry
if raise_error is True:
raise SaltCloudSystemExit('Unable to find {0} in {1}.'.format(key, dict_))
return {}
def get_entry_multi(dict_, pairs, raise_error=True):
for entry in dict_:
if all([entry[key] == value for key, value in pairs]):
return entry
if raise_error is True:
raise SaltCloudSystemExit('Unable to find {0} in {1}.'.format(pairs, dict_))
return {}
def get_endpoint_url_v3(catalog, service_type, region_name):
for service_entry in catalog:
if service_entry['type'] == service_type:
for endpoint_entry in service_entry['endpoints']:
if (endpoint_entry['region'] == region_name and
endpoint_entry['interface'] == 'public'):
return endpoint_entry['url']
return None
def sanatize_novaclient(kwargs):
variables = (
'username', 'api_key', 'project_id', 'auth_url', 'insecure',
'timeout', 'proxy_tenant_id', 'proxy_token', 'region_name',
'endpoint_type', 'extensions', 'service_type', 'service_name',
'volume_service_name', 'timings', 'bypass_url', 'os_cache',
'no_cache', 'http_log_debug', 'auth_system', 'auth_plugin',
'auth_token', 'cacert', 'tenant_id'
)
ret = {}
for var in kwargs:
if var in variables:
ret[var] = kwargs[var]
return ret
# Function alias to not shadow built-ins
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
# The following is a list of functions that need to be incorporated in the
# nova module. This list should be updated as functions are added.
#
# absolute-limits Print a list of absolute limits for a user
# actions Retrieve server actions.
# add-fixed-ip Add new IP address to network.
# aggregate-add-host Add the host to the specified aggregate.
# aggregate-create Create a new aggregate with the specified details.
# aggregate-delete Delete the aggregate by its id.
# aggregate-details Show details of the specified aggregate.
# aggregate-list Print a list of all aggregates.
# aggregate-remove-host
# Remove the specified host from the specified aggregate.
# aggregate-set-metadata
# Update the metadata associated with the aggregate.
# aggregate-update Update the aggregate's name and optionally
# availability zone.
# cloudpipe-create Create a cloudpipe instance for the given project
# cloudpipe-list Print a list of all cloudpipe instances.
# console-log Get console log output of a server.
# credentials Show user credentials returned from auth
# describe-resource Show details about a resource
# diagnostics Retrieve server diagnostics.
# dns-create Create a DNS entry for domain, name and ip.
# dns-create-private-domain
# Create the specified DNS domain.
# dns-create-public-domain
# Create the specified DNS domain.
# dns-delete Delete the specified DNS entry.
# dns-delete-domain Delete the specified DNS domain.
# dns-domains Print a list of available dns domains.
# dns-list List current DNS entries for domain and ip or domain
# and name.
# endpoints Discover endpoints that get returned from the
# authenticate services
# get-vnc-console Get a vnc console to a server.
# host-action Perform a power action on a host.
# host-update Update host settings.
# image-create Create a new image by taking a snapshot of a running
# server.
# image-delete Delete an image.
# live-migration Migrates a running instance to a new machine.
# meta Set or Delete metadata on a server.
# migrate Migrate a server.
# pause Pause a server.
# rate-limits Print a list of rate limits for a user
# reboot Reboot a server.
# rebuild Shutdown, re-image, and re-boot a server.
# remove-fixed-ip Remove an IP address from a server.
# rename Rename a server.
# rescue Rescue a server.
# resize Resize a server.
# resize-confirm Confirm a previous resize.
# resize-revert Revert a previous resize (and return to the previous
# VM).
# root-password Change the root password for a server.
# secgroup-add-group-rule
# Add a source group rule to a security group.
# secgroup-add-rule Add a rule to a security group.
# secgroup-delete-group-rule
# Delete a source group rule from a security group.
# secgroup-delete-rule
# Delete a rule from a security group.
# secgroup-list-rules
# List rules for a security group.
# ssh SSH into a server.
# unlock Unlock a server.
# unpause Unpause a server.
# unrescue Unrescue a server.
# usage-list List usage data for all tenants
# volume-list List all the volumes.
# volume-snapshot-create
# Add a new snapshot.
# volume-snapshot-delete
# Remove a snapshot.
# volume-snapshot-list
# List all the snapshots.
# volume-snapshot-show
# Show details about a snapshot.
# volume-type-create Create a new volume type.
# volume-type-delete Delete a specific flavor
# volume-type-list Print a list of available 'volume types'.
# x509-create-cert Create x509 cert for a user in tenant
# x509-get-root-cert Fetches the x509 root cert.
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova._get_version_from_url
|
python
|
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
|
Exctract API version from provided URL
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L268-L281
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova._discover_ks_version
|
python
|
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
|
Keystone API version discovery
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L283-L295
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_show_libcloud
|
python
|
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
|
Make output look like libcloud output for consistency
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L483-L494
|
[
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def server_show(self, server_id):\n '''\n Show details of one server\n '''\n ret = {}\n try:\n servers = self.server_list_detailed()\n except AttributeError:\n raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')\n for server_name, server in six.iteritems(servers):\n if six.text_type(server['id']) == server_id:\n ret[server_name] = server\n return ret\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.boot
|
python
|
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
|
Boot a cloud server.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L496-L535
|
[
"def _parse_block_device_mapping_v2(block_device=None, boot_volume=None, snapshot=None, ephemeral=None, swap=None):\n bdm = []\n if block_device is None:\n block_device = []\n if ephemeral is None:\n ephemeral = []\n\n if boot_volume is not None:\n bdm_dict = {'uuid': boot_volume, 'source_type': 'volume',\n 'destination_type': 'volume', 'boot_index': 0,\n 'delete_on_termination': False}\n bdm.append(bdm_dict)\n\n if snapshot is not None:\n bdm_dict = {'uuid': snapshot, 'source_type': 'snapshot',\n 'destination_type': 'volume', 'boot_index': 0,\n 'delete_on_termination': False}\n bdm.append(bdm_dict)\n\n for device_spec in block_device:\n bdm_dict = {}\n\n for key, value in six.iteritems(device_spec):\n bdm_dict[CLIENT_BDM2_KEYS[key]] = value\n\n # Convert the delete_on_termination to a boolean or set it to true by\n # default for local block devices when not specified.\n if 'delete_on_termination' in bdm_dict:\n action = bdm_dict['delete_on_termination']\n bdm_dict['delete_on_termination'] = (action == 'remove')\n elif bdm_dict.get('destination_type') == 'local':\n bdm_dict['delete_on_termination'] = True\n\n bdm.append(bdm_dict)\n\n for ephemeral_spec in ephemeral:\n bdm_dict = {'source_type': 'blank', 'destination_type': 'local',\n 'boot_index': -1, 'delete_on_termination': True}\n if 'size' in ephemeral_spec:\n bdm_dict['volume_size'] = ephemeral_spec['size']\n if 'format' in ephemeral_spec:\n bdm_dict['guest_format'] = ephemeral_spec['format']\n\n bdm.append(bdm_dict)\n\n if swap is not None:\n bdm_dict = {'source_type': 'blank', 'destination_type': 'local',\n 'boot_index': -1, 'delete_on_termination': True,\n 'guest_format': 'swap', 'volume_size': swap}\n bdm.append(bdm_dict)\n\n return bdm\n",
"def server_show_libcloud(self, uuid):\n '''\n Make output look like libcloud output for consistency\n '''\n server_info = self.server_show(uuid)\n server = next(six.itervalues(server_info))\n server_name = next(six.iterkeys(server_info))\n if not hasattr(self, 'password'):\n self.password = None\n ret = NovaServer(server_name, server, self.password)\n\n return ret\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.root_password
|
python
|
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
|
Change server(uuid's) root password
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L543-L548
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_by_name
|
python
|
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
|
Find a server by its name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L550-L556
|
[
"def server_show_libcloud(self, uuid):\n '''\n Make output look like libcloud output for consistency\n '''\n server_info = self.server_show(uuid)\n server = next(six.itervalues(server_info))\n server_name = next(six.iterkeys(server_info))\n if not hasattr(self, 'password'):\n self.password = None\n ret = NovaServer(server_name, server, self.password)\n\n return ret\n",
"def server_list(self):\n '''\n List servers\n '''\n nt_ks = self.compute_conn\n ret = {}\n for item in nt_ks.servers.list():\n try:\n ret[item.name] = {\n 'id': item.id,\n 'name': item.name,\n 'state': item.status,\n 'accessIPv4': item.accessIPv4,\n 'accessIPv6': item.accessIPv6,\n 'flavor': {'id': item.flavor['id'],\n 'links': item.flavor['links']},\n 'image': {'id': item.image['id'] if item.image else 'Boot From Volume',\n 'links': item.image['links'] if item.image else ''},\n }\n except TypeError:\n pass\n return ret\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova._volume_get
|
python
|
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
|
Organize information about a volume from the volume_id
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L558-L573
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_list
|
python
|
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
|
List all block volumes
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L575-L593
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_show
|
python
|
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
|
Show one volume
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L595-L611
|
[
"def volume_list(self, search_opts=None):\n '''\n List all block volumes\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volumes = nt_ks.volumes.list(search_opts=search_opts)\n response = {}\n for volume in volumes:\n response[volume.display_name] = {\n 'name': volume.display_name,\n 'size': volume.size,\n 'id': volume.id,\n 'description': volume.display_description,\n 'attachments': volume.attachments,\n 'status': volume.status\n }\n return response\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_create
|
python
|
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
|
Create a block device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L613-L629
|
[
"def _volume_get(self, volume_id):\n '''\n Organize information about a volume from the volume_id\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volume = nt_ks.volumes.get(volume_id)\n response = {'name': volume.display_name,\n 'size': volume.size,\n 'id': volume.id,\n 'description': volume.display_description,\n 'attachments': volume.attachments,\n 'status': volume.status\n }\n return response\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_delete
|
python
|
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
|
Delete a block device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L631-L645
|
[
" def volume_show(self, name):\n '''\n Show one volume\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volumes = self.volume_list(\n search_opts={'display_name': name},\n )\n volume = volumes[name]\n# except Exception as esc:\n# # volume doesn't exist\n# log.error(esc.strerror)\n# return {'name': name, 'status': 'deleted'}\n\n return volume\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_detach
|
python
|
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
|
Detach a block device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L647-L681
|
[
"def _volume_get(self, volume_id):\n '''\n Organize information about a volume from the volume_id\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volume = nt_ks.volumes.get(volume_id)\n response = {'name': volume.display_name,\n 'size': volume.size,\n 'id': volume.id,\n 'description': volume.display_description,\n 'attachments': volume.attachments,\n 'status': volume.status\n }\n return response\n",
" def volume_show(self, name):\n '''\n Show one volume\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volumes = self.volume_list(\n search_opts={'display_name': name},\n )\n volume = volumes[name]\n# except Exception as esc:\n# # volume doesn't exist\n# log.error(esc.strerror)\n# return {'name': name, 'status': 'deleted'}\n\n return volume\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.volume_attach
|
python
|
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
|
Attach a block device
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L683-L719
|
[
"def server_by_name(self, name):\n '''\n Find a server by its name\n '''\n return self.server_show_libcloud(\n self.server_list().get(name, {}).get('id', '')\n )\n",
"def _volume_get(self, volume_id):\n '''\n Organize information about a volume from the volume_id\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volume = nt_ks.volumes.get(volume_id)\n response = {'name': volume.display_name,\n 'size': volume.size,\n 'id': volume.id,\n 'description': volume.display_description,\n 'attachments': volume.attachments,\n 'status': volume.status\n }\n return response\n",
" def volume_show(self, name):\n '''\n Show one volume\n '''\n if self.volume_conn is None:\n raise SaltCloudSystemExit('No cinder endpoint available')\n nt_ks = self.volume_conn\n volumes = self.volume_list(\n search_opts={'display_name': name},\n )\n volume = volumes[name]\n# except Exception as esc:\n# # volume doesn't exist\n# log.error(esc.strerror)\n# return {'name': name, 'status': 'deleted'}\n\n return volume\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.suspend
|
python
|
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
|
Suspend a server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L721-L727
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.resume
|
python
|
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
|
Resume a server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L729-L735
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.lock
|
python
|
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
|
Lock an instance
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L737-L743
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.delete
|
python
|
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
|
Delete a server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L745-L751
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_list
|
python
|
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
|
Return a list of available flavors (nova flavor-list)
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L753-L774
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_create
|
python
|
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
|
Create a flavor
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L778-L797
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_delete
|
python
|
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
|
Delete a flavor
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L799-L805
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_access_list
|
python
|
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
|
Return a list of project IDs assigned to flavor ID
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L807-L817
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_access_add
|
python
|
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
|
Add a project to the flavor access list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L819-L828
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.flavor_access_remove
|
python
|
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
|
Remove a project from the flavor access list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L830-L839
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.keypair_list
|
python
|
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
|
List keypairs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L841-L853
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.keypair_add
|
python
|
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
|
Add a keypair
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L855-L867
|
[
"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"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.keypair_delete
|
python
|
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
|
Delete a keypair
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L869-L875
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.image_show
|
python
|
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
|
Show image details and metadata
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L877-L901
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.image_list
|
python
|
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
|
List server images
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L903-L929
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.image_meta_set
|
python
|
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
|
Set image metadata
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L933-L948
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.image_meta_delete
|
python
|
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
|
Delete image metadata
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L950-L966
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_list
|
python
|
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
|
List servers
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L968-L989
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_list_min
|
python
|
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
|
List minimal information about servers
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L991-L1005
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_list_detailed
|
python
|
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
|
Detailed list of servers
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1007-L1067
| null |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
saltstack/salt
|
salt/utils/openstack/nova.py
|
SaltNova.server_show
|
python
|
def server_show(self, server_id):
'''
Show details of one server
'''
ret = {}
try:
servers = self.server_list_detailed()
except AttributeError:
raise SaltCloudSystemExit('Corrupt server in server_list_detailed. Remove corrupt servers.')
for server_name, server in six.iteritems(servers):
if six.text_type(server['id']) == server_id:
ret[server_name] = server
return ret
|
Show details of one server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/nova.py#L1069-L1081
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def server_list_detailed(self):\n '''\n Detailed list of servers\n '''\n nt_ks = self.compute_conn\n ret = {}\n for item in nt_ks.servers.list():\n try:\n ret[item.name] = {\n 'OS-EXT-SRV-ATTR': {},\n 'OS-EXT-STS': {},\n 'accessIPv4': item.accessIPv4,\n 'accessIPv6': item.accessIPv6,\n 'addresses': item.addresses,\n 'created': item.created,\n 'flavor': {'id': item.flavor['id'],\n 'links': item.flavor['links']},\n 'hostId': item.hostId,\n 'id': item.id,\n 'image': {'id': item.image['id'] if item.image else 'Boot From Volume',\n 'links': item.image['links'] if item.image else ''},\n 'key_name': item.key_name,\n 'links': item.links,\n 'metadata': item.metadata,\n 'name': item.name,\n 'state': item.status,\n 'tenant_id': item.tenant_id,\n 'updated': item.updated,\n 'user_id': item.user_id,\n }\n except TypeError:\n continue\n\n ret[item.name]['progress'] = getattr(item, 'progress', '0')\n\n if hasattr(item.__dict__, 'OS-DCF:diskConfig'):\n ret[item.name]['OS-DCF'] = {\n 'diskConfig': item.__dict__['OS-DCF:diskConfig']\n }\n if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):\n ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \\\n item.__dict__['OS-EXT-SRV-ATTR:host']\n if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):\n ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \\\n item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']\n if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):\n ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \\\n item.__dict__['OS-EXT-SRV-ATTR:instance_name']\n if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):\n ret[item.name]['OS-EXT-STS']['power_state'] = \\\n item.__dict__['OS-EXT-STS:power_state']\n if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):\n ret[item.name]['OS-EXT-STS']['task_state'] = \\\n item.__dict__['OS-EXT-STS:task_state']\n if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):\n ret[item.name]['OS-EXT-STS']['vm_state'] = \\\n item.__dict__['OS-EXT-STS:vm_state']\n if hasattr(item.__dict__, 'security_groups'):\n ret[item.name]['security_groups'] = \\\n item.__dict__['security_groups']\n return ret\n"
] |
class SaltNova(object):
'''
Class for all novaclient functions
'''
extensions = []
def __init__(
self,
username,
project_id,
auth_url,
region_name=None,
password=None,
os_auth_plugin=None,
use_keystoneauth=False,
**kwargs
):
'''
Set up nova credentials
'''
if all([use_keystoneauth, HAS_KEYSTONEAUTH]):
self._new_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
else:
self._old_init(username=username,
project_id=project_id,
auth_url=auth_url,
region_name=region_name,
password=password,
os_auth_plugin=os_auth_plugin,
**kwargs)
def _get_version_from_url(self, url):
'''
Exctract API version from provided URL
'''
regex = re.compile(r"^https?:\/\/.*\/(v[0-9])(\.[0-9])?(\/)?$")
try:
ver = regex.match(url)
if ver.group(1):
retver = ver.group(1)
if ver.group(2):
retver = retver + ver.group(2)
return retver
except AttributeError:
return ''
def _discover_ks_version(self, url):
'''
Keystone API version discovery
'''
result = salt.utils.http.query(url, backend='requests', status=True, decode=True, decode_type='json')
versions = json.loads(result['body'])
try:
links = [ver['links'] for ver in versions['versions']['values'] if ver['status'] == 'stable'][0] \
if result['status'] == 300 else versions['version']['links']
resurl = [link['href'] for link in links if link['rel'] == 'self'][0]
return self._get_version_from_url(resurl)
except KeyError as exc:
raise SaltCloudSystemExit('KeyError: key {0} not found in API response: {1}'.format(exc, versions))
def _new_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, auth=None, **kwargs):
if auth is None:
auth = {}
ks_version = self._get_version_from_url(auth_url)
if not ks_version:
ks_version = self._discover_ks_version(auth_url)
auth_url = '{0}/{1}'.format(auth_url, ks_version)
loader = keystoneauth1.loading.get_plugin_loader(os_auth_plugin or 'password')
self.client_kwargs = kwargs.copy()
self.kwargs = auth.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.client_kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_name'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['password'] = password
if ks_version == 'v3':
self.kwargs['project_id'] = kwargs.get('project_id')
self.kwargs['project_name'] = kwargs.get('project_name')
self.kwargs['user_domain_name'] = kwargs.get('user_domain_name', 'default')
self.kwargs['project_domain_name'] = kwargs.get('project_domain_name', 'default')
self.client_kwargs['region_name'] = region_name
self.client_kwargs['service_type'] = 'compute'
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.client_kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.client_kwargs = self.kwargstruct.__dict__
# Requires novaclient version >= 2.6.1
self.version = six.text_type(kwargs.get('version', 2))
self.client_kwargs = sanatize_novaclient(self.client_kwargs)
options = loader.load_from_options(**self.kwargs)
self.session = keystoneauth1.session.Session(auth=options)
conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
self.kwargs['auth_token'] = conn.client.session.get_token()
identity_service_type = kwargs.get('identity_service_type', 'identity')
self.catalog = conn.client.session.get('/' + ks_version + '/auth/catalog',
endpoint_filter={'service_type': identity_service_type}
).json().get('catalog', [])
for ep_type in self.catalog:
if ep_type['type'] == identity_service_type:
for ep_id in ep_type['endpoints']:
ep_ks_version = self._get_version_from_url(ep_id['url'])
if not ep_ks_version:
ep_id['url'] = '{0}/{1}'.format(ep_id['url'], ks_version)
if ks_version == 'v3':
self._v3_setup(region_name)
else:
self._v2_setup(region_name)
def _old_init(self, username, project_id, auth_url, region_name, password, os_auth_plugin, **kwargs):
self.kwargs = kwargs.copy()
if not self.extensions:
if hasattr(OpenStackComputeShell, '_discover_extensions'):
self.extensions = OpenStackComputeShell()._discover_extensions('2.0')
else:
self.extensions = client.discover_extensions('2.0')
for extension in self.extensions:
extension.run_hooks('__pre_parse_args__')
self.kwargs['extensions'] = self.extensions
self.kwargs['username'] = username
self.kwargs['project_id'] = project_id
self.kwargs['auth_url'] = auth_url
self.kwargs['region_name'] = region_name
self.kwargs['service_type'] = 'compute'
# used in novaclient extensions to see if they are rackspace or not, to know if it needs to load
# the hooks for that extension or not. This is cleaned up by sanatize_novaclient
self.kwargs['os_auth_url'] = auth_url
if os_auth_plugin is not None:
novaclient.auth_plugin.discover_auth_systems()
auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_plugin)
self.kwargs['auth_plugin'] = auth_plugin
self.kwargs['auth_system'] = os_auth_plugin
if not self.kwargs.get('api_key', None):
self.kwargs['api_key'] = password
# This has to be run before sanatize_novaclient before extra variables are cleaned out.
if hasattr(self, 'extensions'):
# needs an object, not a dictionary
self.kwargstruct = KwargsStruct(**self.kwargs)
for extension in self.extensions:
extension.run_hooks('__post_parse_args__', self.kwargstruct)
self.kwargs = self.kwargstruct.__dict__
self.kwargs = sanatize_novaclient(self.kwargs)
# Requires novaclient version >= 2.6.1
self.kwargs['version'] = six.text_type(kwargs.get('version', 2))
conn = client.Client(**self.kwargs)
try:
conn.client.authenticate()
except novaclient.exceptions.AmbiguousEndpoints:
raise SaltCloudSystemExit(
"Nova provider requires a 'region_name' to be specified"
)
self.kwargs['auth_token'] = conn.client.auth_token
self.catalog = conn.client.service_catalog.catalog['access']['serviceCatalog']
self._v2_setup(region_name)
def _v3_setup(self, region_name):
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'compute', region_name)
log.debug('Using Nova bypass_url: %s', self.client_kwargs['bypass_url'])
self.compute_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.client_kwargs['bypass_url'] = get_endpoint_url_v3(self.catalog, 'volume', region_name)
log.debug('Using Cinder bypass_url: %s', self.client_kwargs['bypass_url'])
self.volume_conn = client.Client(version=self.version, session=self.session, **self.client_kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def _v2_setup(self, region_name):
if region_name is not None:
servers_endpoints = get_entry(self.catalog, 'type', 'compute')['endpoints']
self.kwargs['bypass_url'] = get_entry(
servers_endpoints,
'region',
region_name
)['publicURL']
self.compute_conn = client.Client(**self.kwargs)
volume_endpoints = get_entry(self.catalog, 'type', 'volume', raise_error=False).get('endpoints', {})
if volume_endpoints:
if region_name is not None:
self.kwargs['bypass_url'] = get_entry(
volume_endpoints,
'region',
region_name
)['publicURL']
self.volume_conn = client.Client(**self.kwargs)
if hasattr(self, 'extensions'):
self.expand_extensions()
else:
self.volume_conn = None
def expand_extensions(self):
for connection in (self.compute_conn, self.volume_conn):
if connection is None:
continue
for extension in self.extensions:
for attr in extension.module.__dict__:
if not inspect.isclass(getattr(extension.module, attr)):
continue
for key, value in six.iteritems(connection.__dict__):
if not isinstance(value, novaclient.base.Manager):
continue
if value.__class__.__name__ == attr:
setattr(connection, key, extension.manager_class(connection))
def get_catalog(self):
'''
Return service catalog
'''
return self.catalog
def server_show_libcloud(self, uuid):
'''
Make output look like libcloud output for consistency
'''
server_info = self.server_show(uuid)
server = next(six.itervalues(server_info))
server_name = next(six.iterkeys(server_info))
if not hasattr(self, 'password'):
self.password = None
ret = NovaServer(server_name, server, self.password)
return ret
def boot(self, name, flavor_id=0, image_id=0, timeout=300, **kwargs):
'''
Boot a cloud server.
'''
nt_ks = self.compute_conn
kwargs['name'] = name
kwargs['flavor'] = flavor_id
kwargs['image'] = image_id or None
ephemeral = kwargs.pop('ephemeral', [])
block_device = kwargs.pop('block_device', [])
boot_volume = kwargs.pop('boot_volume', None)
snapshot = kwargs.pop('snapshot', None)
swap = kwargs.pop('swap', None)
kwargs['block_device_mapping_v2'] = _parse_block_device_mapping_v2(
block_device=block_device, boot_volume=boot_volume, snapshot=snapshot,
ephemeral=ephemeral, swap=swap
)
response = nt_ks.servers.create(**kwargs)
self.uuid = response.id
self.password = getattr(response, 'adminPass', None)
start = time.time()
trycount = 0
while True:
trycount += 1
try:
return self.server_show_libcloud(self.uuid)
except Exception as exc:
log.debug(
'Server information not yet available: %s', exc
)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying server_show() (try %s)', trycount
)
def show_instance(self, name):
'''
Find a server by its name (libcloud)
'''
return self.server_by_name(name)
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password)
def server_by_name(self, name):
'''
Find a server by its name
'''
return self.server_show_libcloud(
self.server_list().get(name, {}).get('id', '')
)
def _volume_get(self, volume_id):
'''
Organize information about a volume from the volume_id
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volume = nt_ks.volumes.get(volume_id)
response = {'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_list(self, search_opts=None):
'''
List all block volumes
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = nt_ks.volumes.list(search_opts=search_opts)
response = {}
for volume in volumes:
response[volume.display_name] = {
'name': volume.display_name,
'size': volume.size,
'id': volume.id,
'description': volume.display_description,
'attachments': volume.attachments,
'status': volume.status
}
return response
def volume_show(self, name):
'''
Show one volume
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
volumes = self.volume_list(
search_opts={'display_name': name},
)
volume = volumes[name]
# except Exception as esc:
# # volume doesn't exist
# log.error(esc.strerror)
# return {'name': name, 'status': 'deleted'}
return volume
def volume_create(self, name, size=100, snapshot=None, voltype=None,
availability_zone=None):
'''
Create a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
response = nt_ks.volumes.create(
size=size,
display_name=name,
volume_type=voltype,
snapshot_id=snapshot,
availability_zone=availability_zone
)
return self._volume_get(response.id)
def volume_delete(self, name):
'''
Delete a block device
'''
if self.volume_conn is None:
raise SaltCloudSystemExit('No cinder endpoint available')
nt_ks = self.volume_conn
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if volume['status'] == 'deleted':
return volume
response = nt_ks.volumes.delete(volume['id'])
return volume
def volume_detach(self,
name,
timeout=300):
'''
Detach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
)
def volume_attach(self,
name,
server_name,
device='/dev/xvdb',
timeout=300):
'''
Attach a block device
'''
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
server = self.server_by_name(server_name)
response = self.compute_conn.volumes.create_server_volume(
server.id,
volume['id'],
device=device
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'in-use':
return response
except Exception as exc:
log.debug('Volume is attaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %s seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %s)', trycount
)
def suspend(self, instance_id):
'''
Suspend a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.suspend(instance_id)
return True
def resume(self, instance_id):
'''
Resume a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.resume(instance_id)
return True
def lock(self, instance_id):
'''
Lock an instance
'''
nt_ks = self.compute_conn
response = nt_ks.servers.lock(instance_id)
return True
def delete(self, instance_id):
'''
Delete a server
'''
nt_ks = self.compute_conn
response = nt_ks.servers.delete(instance_id)
return True
def flavor_list(self, **kwargs):
'''
Return a list of available flavors (nova flavor-list)
'''
nt_ks = self.compute_conn
ret = {}
for flavor in nt_ks.flavors.list(**kwargs):
links = {}
for link in flavor.links:
links[link['rel']] = link['href']
ret[flavor.name] = {
'disk': flavor.disk,
'id': flavor.id,
'name': flavor.name,
'ram': flavor.ram,
'swap': flavor.swap,
'vcpus': flavor.vcpus,
'links': links,
}
if hasattr(flavor, 'rxtx_factor'):
ret[flavor.name]['rxtx_factor'] = flavor.rxtx_factor
return ret
list_sizes = flavor_list
def flavor_create(self,
name, # pylint: disable=C0103
flavor_id=0, # pylint: disable=C0103
ram=0,
disk=0,
vcpus=1,
is_public=True):
'''
Create a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.create(
name=name, flavorid=flavor_id, ram=ram, disk=disk, vcpus=vcpus, is_public=is_public
)
return {'name': name,
'id': flavor_id,
'ram': ram,
'disk': disk,
'vcpus': vcpus,
'is_public': is_public}
def flavor_delete(self, flavor_id): # pylint: disable=C0103
'''
Delete a flavor
'''
nt_ks = self.compute_conn
nt_ks.flavors.delete(flavor_id)
return 'Flavor deleted: {0}'.format(flavor_id)
def flavor_access_list(self, **kwargs):
'''
Return a list of project IDs assigned to flavor ID
'''
flavor_id = kwargs.get('flavor_id')
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.list(flavor=flavor_id, **kwargs)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_add(self, flavor_id, project_id):
'''
Add a project to the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def flavor_access_remove(self, flavor_id, project_id):
'''
Remove a project from the flavor access list
'''
nt_ks = self.compute_conn
ret = {flavor_id: []}
flavor_accesses = nt_ks.flavor_access.remove_tenant_access(flavor_id, project_id)
for project in flavor_accesses:
ret[flavor_id].append(project.tenant_id)
return ret
def keypair_list(self):
'''
List keypairs
'''
nt_ks = self.compute_conn
ret = {}
for keypair in nt_ks.keypairs.list():
ret[keypair.name] = {
'name': keypair.name,
'fingerprint': keypair.fingerprint,
'public_key': keypair.public_key,
}
return ret
def keypair_add(self, name, pubfile=None, pubkey=None):
'''
Add a keypair
'''
nt_ks = self.compute_conn
if pubfile:
with salt.utils.files.fopen(pubfile, 'r') as fp_:
pubkey = salt.utils.stringutils.to_unicode(fp_.read())
if not pubkey:
return False
nt_ks.keypairs.create(name, public_key=pubkey)
ret = {'name': name, 'pubkey': pubkey}
return ret
def keypair_delete(self, name):
'''
Delete a keypair
'''
nt_ks = self.compute_conn
nt_ks.keypairs.delete(name)
return 'Keypair deleted: {0}'.format(name)
def image_show(self, image_id):
'''
Show image details and metadata
'''
nt_ks = self.compute_conn
image = nt_ks.images.get(image_id)
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret['minRam'] = image.minRam
return ret
def image_list(self, name=None):
'''
List server images
'''
nt_ks = self.compute_conn
ret = {}
for image in nt_ks.images.list():
links = {}
for link in image.links:
links[link['rel']] = link['href']
ret[image.name] = {
'name': image.name,
'id': image.id,
'status': image.status,
'progress': image.progress,
'created': image.created,
'updated': image.updated,
'metadata': image.metadata,
'links': links,
}
if hasattr(image, 'minDisk'):
ret[image.name]['minDisk'] = image.minDisk
if hasattr(image, 'minRam'):
ret[image.name]['minRam'] = image.minRam
if name:
return {name: ret[name]}
return ret
list_images = image_list
def image_meta_set(self,
image_id=None,
name=None,
**kwargs): # pylint: disable=C0103
'''
Set image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.set_meta(image_id, kwargs)
return {image_id: kwargs}
def image_meta_delete(self,
image_id=None, # pylint: disable=C0103
name=None,
keys=None):
'''
Delete image metadata
'''
nt_ks = self.compute_conn
if name:
for image in nt_ks.images.list():
if image.name == name:
image_id = image.id # pylint: disable=C0103
pairs = keys.split(',')
if not image_id:
return {'Error': 'A valid image name or id was not specified'}
nt_ks.images.delete_meta(image_id, pairs)
return {image_id: 'Deleted: {0}'.format(pairs)}
def server_list(self):
'''
List servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'id': item.id,
'name': item.name,
'state': item.status,
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
}
except TypeError:
pass
return ret
def server_list_min(self):
'''
List minimal information about servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list(detailed=False):
try:
ret[item.name] = {
'id': item.id,
'state': 'Running'
}
except TypeError:
pass
return ret
def server_list_detailed(self):
'''
Detailed list of servers
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.servers.list():
try:
ret[item.name] = {
'OS-EXT-SRV-ATTR': {},
'OS-EXT-STS': {},
'accessIPv4': item.accessIPv4,
'accessIPv6': item.accessIPv6,
'addresses': item.addresses,
'created': item.created,
'flavor': {'id': item.flavor['id'],
'links': item.flavor['links']},
'hostId': item.hostId,
'id': item.id,
'image': {'id': item.image['id'] if item.image else 'Boot From Volume',
'links': item.image['links'] if item.image else ''},
'key_name': item.key_name,
'links': item.links,
'metadata': item.metadata,
'name': item.name,
'state': item.status,
'tenant_id': item.tenant_id,
'updated': item.updated,
'user_id': item.user_id,
}
except TypeError:
continue
ret[item.name]['progress'] = getattr(item, 'progress', '0')
if hasattr(item.__dict__, 'OS-DCF:diskConfig'):
ret[item.name]['OS-DCF'] = {
'diskConfig': item.__dict__['OS-DCF:diskConfig']
}
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:host'):
ret[item.name]['OS-EXT-SRV-ATTR']['host'] = \
item.__dict__['OS-EXT-SRV-ATTR:host']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:hypervisor_hostname'):
ret[item.name]['OS-EXT-SRV-ATTR']['hypervisor_hostname'] = \
item.__dict__['OS-EXT-SRV-ATTR:hypervisor_hostname']
if hasattr(item.__dict__, 'OS-EXT-SRV-ATTR:instance_name'):
ret[item.name]['OS-EXT-SRV-ATTR']['instance_name'] = \
item.__dict__['OS-EXT-SRV-ATTR:instance_name']
if hasattr(item.__dict__, 'OS-EXT-STS:power_state'):
ret[item.name]['OS-EXT-STS']['power_state'] = \
item.__dict__['OS-EXT-STS:power_state']
if hasattr(item.__dict__, 'OS-EXT-STS:task_state'):
ret[item.name]['OS-EXT-STS']['task_state'] = \
item.__dict__['OS-EXT-STS:task_state']
if hasattr(item.__dict__, 'OS-EXT-STS:vm_state'):
ret[item.name]['OS-EXT-STS']['vm_state'] = \
item.__dict__['OS-EXT-STS:vm_state']
if hasattr(item.__dict__, 'security_groups'):
ret[item.name]['security_groups'] = \
item.__dict__['security_groups']
return ret
def secgroup_create(self, name, description):
'''
Create a security group
'''
nt_ks = self.compute_conn
nt_ks.security_groups.create(name, description)
ret = {'name': name, 'description': description}
return ret
def secgroup_delete(self, name):
'''
Delete a security group
'''
nt_ks = self.compute_conn
for item in nt_ks.security_groups.list():
if item.name == name:
nt_ks.security_groups.delete(item.id)
return {name: 'Deleted security group: {0}'.format(name)}
return 'Security group not found: {0}'.format(name)
def secgroup_list(self):
'''
List security groups
'''
nt_ks = self.compute_conn
ret = {}
for item in nt_ks.security_groups.list():
ret[item.name] = {
'name': item.name,
'description': item.description,
'id': item.id,
'tenant_id': item.tenant_id,
'rules': item.rules,
}
return ret
def _item_list(self):
'''
List items
'''
nt_ks = self.compute_conn
ret = []
for item in nt_ks.items.list():
ret.append(item.__dict__)
return ret
def _network_show(self, name, network_lst):
'''
Parse the returned network list
'''
for net in network_lst:
if net.label == name:
return net.__dict__
return {}
def network_show(self, name):
'''
Show network information
'''
nt_ks = self.compute_conn
net_list = nt_ks.networks.list()
return self._network_show(name, net_list)
def network_list(self):
'''
List extra private networks
'''
nt_ks = self.compute_conn
return [network.__dict__ for network in nt_ks.networks.list()]
def _sanatize_network_params(self, kwargs):
'''
Sanatize novaclient network parameters
'''
params = [
'label', 'bridge', 'bridge_interface', 'cidr', 'cidr_v6', 'dns1',
'dns2', 'fixed_cidr', 'gateway', 'gateway_v6', 'multi_host',
'priority', 'project_id', 'vlan_start', 'vpn_start'
]
for variable in six.iterkeys(kwargs): # iterate over a copy, we might delete some
if variable not in params:
del kwargs[variable]
return kwargs
def network_create(self, name, **kwargs):
'''
Create extra private network
'''
nt_ks = self.compute_conn
kwargs['label'] = name
kwargs = self._sanatize_network_params(kwargs)
net = nt_ks.networks.create(**kwargs)
return net.__dict__
def _server_uuid_from_name(self, name):
'''
Get server uuid from name
'''
return self.server_list().get(name, {}).get('id', '')
def virtual_interface_list(self, name):
'''
Get virtual interfaces on slice
'''
nt_ks = self.compute_conn
nets = nt_ks.virtual_interfaces.list(self._server_uuid_from_name(name))
return [network.__dict__ for network in nets]
def virtual_interface_create(self, name, net_name):
'''
Add an interfaces to a slice
'''
nt_ks = self.compute_conn
serverid = self._server_uuid_from_name(name)
networkid = self.network_show(net_name).get('id', None)
if networkid is None:
return {net_name: False}
nets = nt_ks.virtual_interfaces.create(networkid, serverid)
return nets
def floating_ip_pool_list(self):
'''
List all floating IP pools
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
pools = nt_ks.floating_ip_pools.list()
response = {}
for pool in pools:
response[pool.name] = {
'name': pool.name,
}
return response
def floating_ip_list(self):
'''
List floating IPs
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
response = {}
for floating_ip in floating_ips:
response[floating_ip.ip] = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_show(self, ip):
'''
Show info on specific floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ips = nt_ks.floating_ips.list()
for floating_ip in floating_ips:
if floating_ip.ip == ip:
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
return {}
def floating_ip_create(self, pool=None):
'''
Allocate a floating IP
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
floating_ip = nt_ks.floating_ips.create(pool)
response = {
'ip': floating_ip.ip,
'fixed_ip': floating_ip.fixed_ip,
'id': floating_ip.id,
'instance_id': floating_ip.instance_id,
'pool': floating_ip.pool
}
return response
def floating_ip_delete(self, floating_ip):
'''
De-allocate a floating IP
.. versionadded:: 2016.3.0
'''
ip = self.floating_ip_show(floating_ip)
nt_ks = self.compute_conn
return nt_ks.floating_ips.delete(ip)
def floating_ip_associate(self, server_name, floating_ip):
'''
Associate floating IP address to server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.add_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
def floating_ip_disassociate(self, server_name, floating_ip):
'''
Disassociate a floating IP from server
.. versionadded:: 2016.3.0
'''
nt_ks = self.compute_conn
server_ = self.server_by_name(server_name)
server = nt_ks.servers.get(server_.__dict__['id'])
server.remove_floating_ip(floating_ip)
return self.floating_ip_list()[floating_ip]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.